Using awk

Program structure

awk programs consist of a series of patterns, each of which is associated with an action. Each line of input is checked against each of the patterns in turn. For each pattern that matches, the associated action (which can involve multiple steps) is executed. Then the next line is read, and the matching starts over. This process typically continues until all the input has been read.

Patterns may be regular expressions or other, more complex entities.

So, the basic structure of an awk program is as follows:

pattern { action }
pattern { action }

For example:

   $1 == "address"  { print $2, $3 }
This program prints the second and third fields of each input line whose first field is address.

Either the pattern or the action in a pattern-action statement can be omitted. If there is no action with a pattern, the matching line is printed. For example:

   $1 == "name"
If there is no pattern with an action, the action is performed for every input line. For example:
   { print $1, $2 }
Because patterns and actions are both optional, actions are enclosed in braces to distinguish them from patterns. Use of fields and field notation is described in more detail in ``Field variables''.
Next topic: Running awk programs
Previous topic: Fields

© 2003 Caldera International, Inc. All rights reserved.
SCO OpenServer Release 5.0.7 -- 11 February 2003