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!

This article was posted by Matty on 2007-12-03 20:52:00 -0400 -0400