Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep - print line before, don't print match

Tags:

grep

awk

How to easily print line above the match and skip the match itself? grep -A, -B and -o opt do not solve it. Maybe some awk magic?

for example:

$ cat foo.txt
bar
foo
baz
foo

$ cat foo.txt | grep foo-SOMETHING
bar
baz

Edit

  • in case when line 2 and 3 has "foo", then line 1 and 2 should be printed (although I am not very strict here)

Additional feature: consider the example:

bar
foo
baz
foo
foo

This should ideally return

bar
baz
foo
like image 626
Jakub M. Avatar asked Jul 30 '13 09:07

Jakub M.


People also ask

How to print the lines after the match in grep?

Print lines after the match Use the -A option with grep command to print the lines after matched line. The syntax and the example are shown below: syntax: grep -An "pattern" filename Here n is the number of lines to print after the matched line.

How to print the lines before and after the matched line?

To print the lines before the matched line use the -B option with grep command. The syntax and the example are shown below: 4. Print lines before and after match We can print both the lines above and below the matched line. Use the -a option with the grep command.

How to use grep command in Linux system?

The grep command in unix or linux system is used to print the lines that match a given pattern. By default the grep command displays only the matching lines. We can change the behaviour of the grep command to print the lines that are above and below the matched line. 1.

How to show lines before and after the match in Linux?

Grep: show lines before and after the match in Linux You can add some additional parameters to your grep command, to search for keywords or phrases in files, to also show you the files that match before or after your match.


1 Answers

awk '!/foo/ { line = $0 }
     /foo/ { print line }' foo.txt

The first clause saves each non-foo line in a variable. The second clause prints the most recent saved line when the line matches foo.

This also works (and handles the case where you have two foo lines in a row):

awk '/foo/ {print line}
     {line = $0}' foo.txt

With grep you can do:

grep -B 1 foo foo.txt | grep -vE 'foo|^--$'

The second command filters out the foo lines and the dividers that are printed between the matching blocks.

like image 68
Barmar Avatar answered Oct 05 '22 03:10

Barmar