(n)awk: print matching lines and some more

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

3 Responses to “(n)awk: print matching lines and some more”

  1. Chris Gerhard Says:

    Cool. A bit less typing:
    nawk ‘/usb/ { a=-5} a++ < 0 { print NR, $0 }’ /var/adm/messages

  2. Bernd Finger Says:

    Thanks, Chris. Very useful especially for those working on Mac OS X with a German keyboard (http://blogs.sun.com/blogfinger/entry/mac_os_x_often_used) – avoids typing two more curly braces…
    I don’t like the additional spaces you inserted, however 😉

  3. Chris Gerhard Says:

    Bernd, surely the space bar is really big even on a German Keyboard!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


%d bloggers like this: