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


Simple patterns

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

An instruction of the form:
pattern {actions}
indicates that awk is to perform the given set of actions on every record that meets a certain set of conditions. The conditions are given by the pattern part of the instruction.
The pattern of an instruction often looks for records that have a particular value in some field. The notation $1 stands for the first field of a record, $2 stands for the second field, and so on. For example, here's a simple awk instruction:
$2 == "jogging" { print }
The notation == stands for "is equal to". Therefore, the instruction means: If the second field in a record is jogging, print the entire record.
This instruction is a complete awk program. If you ran this program on the hobbies file, awk would look through the file record by record (line by line). Whenever a line had jogging as its second field, awk would print the complete record. The printout from the program would be:
Katie   jogging          14     120.00
John    jogging           8      30.00
Lori    jogging           5      30.00
Let's take another example. Ask yourself what the following awk program does.
$1 == "John" { print }
As you probably guessed, it prints every record that has John as its first field. The printout from the program would be:
John    role playing      8     100.00
John    jogging           8      30.00
You could perform the same sort of search on any text database. The only difference is that databases tend to contain a great deal more data than this example.
If an awk instruction does not contain an action, print is assumed. The preceding examples use the print action; however, this action does not need to be written explicitly. You could write the programs as:
$2 == "jogging"
and:
$1 == "John"
and they would have exactly the same effect.
On the other hand, you can specify an action and leave out the pattern part of an instruction. In this case, awk applies the action part of the instruction to every record in the file. For example:
{ print }
is a complete awk program that displays every record in the data file.

Go to the previous page Go to the next page




Copyright IBM Corporation 1990, 2014