z/OS UNIX System Services User's Guide
Previous topic | Next topic | Contents | Contact z/OS | Library | PDF


Using special patterns

z/OS UNIX System Services User's Guide
SA23-2279-00

BEGIN and END are two special patterns.
BEGIN
When an instruction has BEGIN as its pattern, awk performs the associated action before looking at any of the records in the data file.
END
When an instruction has END as its pattern, awk performs the associated action after looking at all records in the data files specified on the command line.
Consider the action:
count = count + 1
awk first finds the value of:
count + 1
and then assigns this value to count. Thus this action increases the value of count by 1. In a program, you can use this sort of action to count how many people have jogging as a hobby:
BEGIN { count = 0 }
$2 == "jogging" { count = count + 1 }
END { printf "%d people like jogging.\n", count }
Let's look at this program line by line.
BEGIN { count = 0 }
In this example, awk begins by assigning the value 0 to count:
$2 == "jogging" { count = count + 1 }
adds 1 to count every time awk finds a record with jogging in the second field.
END { printf "%d people like jogging.\n", count }
When awk has looked at all the records, the printf action prints the count of people who jog. The output from the program is:
3 people like jogging.
Notice how the value of count was printed in place of the %d placeholder. For more information about using a placeholder, see Placeholders.

Go to the previous page Go to the next page




Copyright IBM Corporation 1990, 2014