Matching grep patterns that exclude parts in the output

Is it possible to use only one combination of grep and regexp to achieve the following. Let's say I have a file like this:

 $ cat f.txt line 1 foo line 2 boo no match line 3 blank line X no match 

I want to combine all the lines starting with the word line , and then the number, but only display what happens after that, so the part that matches (.*) .

 $ grep -E '^line [0-9]+(.*)' f.txt line 1 foo line 2 boo line 3 blank 

Can you tell a coincidence, but not display this part ^line [0-9]+ , for example, do the opposite to grep -o '^line [0-9]+'

So my expected result would look like this:

 $ grep -E ***__magic__*** f.txt foo boo blank 
+4
source share
2 answers

Given your example file:

 $ cat cat_1.txt line 1 foo line 2 boo no match line 3 blank line X no match 

This is easy with Perl:

 perl -lne 'print $1 if /^line \d+ (.*)/' cat_1.txt 

Or with sed :

 sed -En 's/^line [0-9]+ (.*)/\1/p' cat_1.txt 

In any case, the prints:

 foo boo blank 
+1
source

You can use sed

 ~$ cat 1.txt line 1 foo line 2 boo no match line 3 blank line X no match $ grep -E '^line [0-9]' 1.txt | sed 's/^line [0-9] //' foo boo blank 

UPDATED ... or without using sed

 $ grep -E '^line [0-9]' 1.txt | grep -oE '[az]*$' foo boo blank 
+2
source

Source: https://habr.com/ru/post/1445222/


All Articles