Next: , Previous: Very Simple, Up: Getting Started


1.4 An Example with Two Rules

The awk utility reads the input files one line at a time. For each line, awk tries the patterns of each of the rules. If several patterns match, then several actions are run in the order in which they appear in the awk program. If no patterns match, then no actions are run.

After processing all the rules that match the line (and perhaps there are none), awk reads the next line. (However, see Next Statement, and also see Nextfile Statement). This continues until the program reaches the end of the file. For example, the following awk program contains two rules:

     /12/  { print $0 }
     /21/  { print $0 }

The first rule has the string ‘12’ as the pattern and ‘print $0’ as the action. The second rule has the string ‘21’ as the pattern and also has ‘print $0’ as the action. Each rule's action is enclosed in its own pair of braces.

This program prints every line that contains the string ‘12or the string ‘21’. If a line contains both strings, it is printed twice, once by each rule.

This is what happens if we run this program on our two sample data files, BBS-list and inventory-shipped:

     $ awk '/12/ { print $0 }
     >      /21/ { print $0 }' BBS-list inventory-shipped
     -| aardvark     555-5553     1200/300          B
     -| alpo-net     555-3412     2400/1200/300     A
     -| barfly       555-7685     1200/300          A
     -| bites        555-1675     2400/1200/300     A
     -| core         555-2912     1200/300          C
     -| fooey        555-1234     2400/1200/300     B
     -| foot         555-6699     1200/300          B
     -| macfoo       555-6480     1200/300          A
     -| sdace        555-3430     2400/1200/300     A
     -| sabafoo      555-2127     1200/300          C
     -| sabafoo      555-2127     1200/300          C
     -| Jan  21  36  64 620
     -| Apr  21  70  74 514

Note how the line beginning with ‘sabafoo’ in BBS-list was printed twice, once for each rule.