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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…