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
Additional feature: consider the example:
bar
foo
baz
foo
foo
This should ideally return
bar
baz
foo
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With