Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
577 views
in Technique[技术] by (71.8m points)

awk - grep - print line before, don't print match

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...