O'Reilly logo

Learning AWK Programming by Shiwang Kalkhanda

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Multiple rules with AWK

AWK can have multiple pattern-action statements. They are executed in the order in which they appear in the AWK program. If one pattern-action rule matches the same line that was matched with the previous rule, then it is printed twice. This continues until the program reaches the end of the file. In the next example, we have an AWK program with two rules:

$ awk '/maruti/ { print NR, $0 } /2007/ { print NR, $0 }' cars.dat

The output on execution of this code is as follows:

1 maruti          swift       2007        50000       51 maruti          swift       2007        50000       53 maruti          dezire      2009        3100        68 maruti          swift       2009        4100        59 maruti          esteem      1997        98000       112 fiat            punto       2007        45000       3

The record number 1 is printed twice because it matches both rule1 and rule2.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required