Basic structure of a command.
pattern { actions }
pattern {
}
pattern is optional and identifies targeted line or lines to
take action on.
A pattern without an action becomes a grep.
pattern may :
- an actual line number.
NR == 1 { action }
- a range of lines.
NR == 2, NR == 4 { action }
- a regular expression that identifies a line or lines.
/^root/ { action }
- a pair of regular expressions that identifies a block of lines.
/^l/,/^n/ { action }
- any legal combination of these.
NR == 1, /^<body>/ { action }
- testing fields in record (line), The tilde, ~, is required.
$6 ~ /pts/ { print $0, "terminal" }
tests field 6 in each record for the string "pts"
- NOT may be used to invert test condition.
$6 ! ~ /pts/ { print $0, "terminal" }
tests field 6 in each record does not have the string "pts" before
executing the action.
- // supports some egrep style regular expressions. If applied against a
specific field, treate field as a line.
BEGIN - identifies commands to run before processing data file.
Useful for printing header info and setting an alternative field separator.
BEGIN { FS = ":"; print "Today's report" }
END - identifies commands to run after all records processed. Useful
for printing totals and doing calculations on accumulations.
actions specify actions to take on each line. If no pattern match
provided, awk will attempt to act on all lines.
Actions are enclosed in { }, braces.
Individual actions are separated by ;, semi-colons or line breaks.
There may be multiple sets of braces with or without pattern filters.
Action commands are modeled after the C language. But there are a few
simplified commands also available.
{ print $1, $2 }
prints the 1st and second fields of all records. The comma indicates that
the fields will be separated by the standard OFS (output field separator).