Reputation: 69
Maybe a silly question but I have a text file that needs to display everything upto the first pattern match which is a '/'. (all lines contain no blank spaces)
Example.txt:
somename/for/example/
something/as/another/example
thisfile/dir/dir/example
Preferred output:
somename
something
thisfile
I know this grep code will display everything after a matching pattern:
grep -o '/[^\n]*' '/my/file.txt'
So is there any way to do the complete opposite, maybe rm everything after matching pattern or invert to display my preferred output?
Thanks.
Upvotes: 2
Views: 116
Reputation: 174796
You just need to include starting anchor ^
and also the /
in a negated character class.
grep -o '^[^/]*' file
Upvotes: 0
Reputation: 5298
Assuming filename as "file.txt"
cat file.txt | cut -d "/" -f 1
Here, we are cutting the input line with "/" as the delimiter (-d "/"). Then we select the first field (-f 1).
Upvotes: 0
Reputation: 12218
Yu can use a much simpler reg exp:
/[^/]*/
The forward slash after the carat is what you're matching to.
Upvotes: 0
Reputation: 37298
If you're calling an external command like grep
, you can get the same results your require with the sed
command, i.e.
echo "something/as/another/example" | sed 's:/.*::'
something
Instead of focusing on what you want to keep, think about what you want to remove, in this case everything after the first '/' char. This is what this sed
command does.
The leading s
means substitute, the :/.*:
is the pattern to match, with /.*
meaning match the first /' char and all characters after that. The 2nd half of the
sedcommand is the replacement. With
::`, this means replace with nothing.
The traditional idom for sed is to use s/str/rep/
, using /
chars to delimit the search from the replacement, but you can use any character you want after the initial s
(substitute) command.
Some seds expect the /
char, and want a special indication that the following character is the sub/replace delimiter. So if s:/.*::
doesn't work, then s\:/.*::
should work.
IHTH.
Upvotes: 1