(n)awk: print matching lines and some more
Wednesday Jan 21, 2009
I think some of you will find the following (n)awk one-liner useful. I am using it from time to time and thought I should document it so that I do not have to think about where to place the "a++" part, for example.
It will print out lines of a file that match a certain pattern, plus some more lines that follow. In this example, I am searching for lines that contain the string "usb" in /var/adm/messages, and print that line plus 4 more (for more lines, decrement the number in the first curly brackets accordingly). A line number will also be printed out for each line:
$ nawk '/usb/{a=-5}{if (a<0){print NR, $0};a++}' /var/adm/messages










Cool. A bit less typing:
nawk '/usb/ { a=-5} a+...
Thanks, Chris. Very useful especially for those wo...
Bernd, surely the space bar is really big eve...