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 '/foo/{print a}{a=$0}' your_file
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.
Just set p
to the pattern you want:
$ awk '$0~p{print a}{a=$0}' p="foo" file
bar
baz
foo