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!








Fazal Majid on December 3rd, 2007
Or you could use GNU grep’s –after-context option:
ggrep -A 2 test