Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...