
Patterns and Procedures | 773
gawk
This is the Title of the Book, eMatter Edition
Copyright © 2006 O’Reilly & Associates, Inc. All rights reserved.
• BEGIN and END patterns may appear multiple times. The procedures are
merged as if there had been one large procedure.
Except for BEGIN and END, patterns can be combined with the Boolean opera-
tors || (or), && (and), and ! (not). A range of lines can also be specified using
comma-separated patterns:
pattern,pattern
Procedures
Procedures consist of one or more commands, function calls, or variable assign-
ments, separated by newlines or semicolons, and are contained within curly
braces. Commands fall into five groups:
• Variable or array assignments
• Input/Output commands
• Built-in functions
• Control-flow commands
• User-defined functions
Simple Pattern-Procedure Examples
Print first field of each line:
{ print $1 }
Print all lines that contain pattern:
/pattern/
Print first field of lines that contain pattern:
/pattern/ { print $1 }
Select records containing more than two fields:
NF > 2
Interpret input records as a group of lines up to a blank line. Each line is a single
field:
BEGIN { FS = "\n"; RS = "" }
Print fields 2 and 3 in switched order, but only on lines whose first field matches
the string URGENT:
$1 ~ /URGENT/ { print $3, $2 }
Count and print the number of pattern found:
/pattern/ { ++x }
END { print x }
Add numbers in second column and print the total: ...