Programming with awk


If the pattern in a pattern-action statement is omitted, the action is executed for all input lines. The simplest action is to print each line; you can accomplish this with an awk program consisting of a single print statement

   { print }
so the command line
   awk '{ print }' countries
prints each line of countries, copying the file to the standard output. The print statement can also be used to print parts of a record; for instance, the program
   { print $1, $3 }
prints the first and third fields of each record. Thus
   awk '{ print $1, $3 }' countries
produces as output the following sequence of lines:
   USSR 262
   Canada 24
   China 866
   USA 219
   Brazil 116
   Australia 14
   India 637
   Argentina 26
   Sudan 19
   Algeria 18

When printed, items separated by a comma in the print statement are separated by the output field separator which, by default, is a single blank. Each line printed is terminated by the output record separator which, by default, is a newline.

NOTE: In the remainder of this topic, we only show awk programs, without the command line that invokes them. Each complete program can be run either by enclosing it in quotes as the first argument of the awk command, or by putting it in a file and invoking awk with the -f flag, as discussed in ``Usage''. For example, if no input is mentioned, the input is assumed to be the file countries.

Next topic: Formatted printing
Previous topic: The sample input file countries

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004