(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

Comments:

Cool. A bit less typing:

nawk '/usb/ { a=-5} a++ < 0 { print NR, $0 }' /var/adm/messages

Posted by Chris Gerhard on January 21, 2009 at 10:39 AM CET #

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 ;-)

Posted by Bernd Finger on January 21, 2009 at 01:09 PM CET #

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

Posted by Chris Gerhard on January 23, 2009 at 10:37 AM CET #

Post a Comment:
  • HTML Syntax: NOT allowed
About

blogfinger

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today