Printing a set of lines after a pattern match

I had to do some pattern matching last week, and needed a way to print the two lines that occurred after each line that matched a specific string. Since awk provides robust pattern matching, I came up with the following awk command line to grab the information I needed:

$ cat test
foo
1
2
3
foo
1
2
3
$ awk ‘BEGIN { i=0 } /foo/ { while (i < 2 ) { getline; print $0; i++ } i=0}' test
1
2
1
2

I digs me some awk!

4 Comments

Fazal Majid  on December 3rd, 2007

Or you could use GNU grep’s –after-context option:
ggrep -A 2 test

Bernd Eckenfels  on December 3rd, 2007

In that specific case you can use egrep with -A 2 :)

However I am also currntly scripting a log file parser which should be able to keep multiple likes of stacktraces (not starting with date) together, and in that case awk or perl is I guess in order.

Gruss
Bernd

rockmelon  on December 12th, 2007

Classic awk for this is:

nawk ‘NR<=p {print} /foo/ {p=NR+2}’ test

GP>  on March 2nd, 2008

sed -n ‘/foo/!d;n;p;n;p’ test

Leave a Comment