Patterns and Actions

Patterns and actions form the heart of awk programming. It is awk's unconventional data-driven programming model that makes it so attractive and contributes to the brevity of many awk programs.

Patterns

Patterns are constructed from string and/or numeric expressions: when they evaluate to nonzero (true) for the current input record, the associated action is carried out. If a pattern is a bare regular expression, then it means to match the entire input record against that expression, as if you had written $0 ~ /regexp/ instead of just /regexp/. Here are some examples to give the general flavor of selection patterns:

NF =  = 0                                  Select empty records
NF > 3                                   Select records with more than 3 fields
NR < 5                                   Select records 1 through 4
(FNR =  = 3) && (FILENAME ~ /[.][ch]$/)    Select record 3 in C source files
$1 ~ /jones/                             Select records with "jones" in field 1
/[Xx][Mm][Ll]/                           Select records containing "XML", ignoring lettercase
$0 ~ /[Xx][Mm][Ll]/                      Same as preceding selection

awk adds even more power to the matching by permitting range expressions. Two expressions separated by a comma select records from one matching the left expression up to, and including, the record that matches the right expression. If both range expressions match a record, the selection consists of that single record. This behavior is different from that of sed, which looks for the range end only in records that follow the start-of-range record. Here are some examples:

(FNR =  = 3), (FNR =  = 10)                        Select records ...

Get Classic Shell Scripting now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.