DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Programming with awk

Program structure

The basic operation of awk is to scan a set of input lines one after another, searching for lines that match any of a set of patterns or conditions you specify. For each pattern, you can specify an action; this action is performed on each line that matches the pattern. Accordingly, an awk program is a sequence of pattern-action statements, as ``awk program structure and example'' shows.

   Structure:
   

pattern { action } pattern { action } . . .

Example:

$1 == "address" { print $2, $3 }

awk program structure and example

The example in the figure is a typical awk program, consisting of one pattern-action statement. The program prints the second and third fields of each input line whose first field is address. In general, awk programs work by matching each line of input against each of the patterns in turn. For each pattern that matches, the associated action (which may involve multiple steps) is executed. Then the next line is read and the matching starts again. This process typically continues until all the input has been read.

Either the pattern or the action in a pattern-action statement may be omitted. If there is no action with a pattern, as in

   $1 == "name"
the matching line is printed. If there is no pattern with an action, as in
   { print $1, $2 }
the action is performed for every input line. Since patterns and actions are both optional, actions are enclosed in braces to distinguish them from patterns.
Next topic: Usage
Previous topic: Basic awk

© 2005 The SCO Group, Inc. All rights reserved.
SCO OpenServer Release 6.0.0 -- 02 June 2005