The shape of an awk program
An awk program is a list of rules. Each rule has a pattern and an action in braces. For every input line, awk checks each pattern in order, and when the pattern matches, it runs the action. A rule with no pattern runs for every line, and a rule with no action prints the matching line. Special BEGIN and END blocks run once before the first line and once after the last.
printf 'lice 30 paris\nbob 25 rome\n'> people.txt
awk ' print $1 }'people.txtThis prints alice and bob. The rule has no pattern, so it runs for every line, and $1 is the first field of the current line.
Fields and the default separator
awk splits each line into fields on runs of whitespace by default, and leading whitespace is ignored. $1 is the first field, $2 is the second, and so on. $0 is the whole line. NF holds the number of fields in the current line, and $NF is the last field. Because the default splitting ignores repeated spaces, awk handles aligned text more gracefully than cut.
printf ' b c\n'| awk ' print NF, $2, $NF }'The output is 3 b c. The three fields are separated by runs of spaces, and awk counted three of them. The same line with cut would have produced empty fields.
Choosing the separator
Use -F to set the field separator. The value is a regular expression, so -F: splits on colons, and -F'[,;]' splits on commas or semicolons. Setting FS in a BEGIN block does the same thing, and OFS sets the separator that print uses between its arguments.
printf 'lice:x:1001\nbob:x:1002\n'| awk -F: -v OFS='| '' print $1, $3 }'The output is alice | 1001 and bob | 1002. The comma in print inserts the output separator, which is a space by default. Here the option -v OFS sets it to a vertical bar with spaces around it.
In awk, a comma between two items in print inserts OFS, and writing the items next to each other concatenates them with no separator. Mixing these up is a frequent source of unexpected output.
Patterns: choosing lines
A pattern can be a comparison, a regular expression between slashes, or a combination with && and ||. Comparisons on fields compare numbers when both sides look numeric. The rule below prints the names of people older than 26.
awk '2 > 26 { print $1 }'people.txtThis prints alice, because 30 is greater than 26 and 25 is not. A regex pattern such as /rome/ matches the whole line, so it is written without a field number. Use $3 ~ /rome/ to match only the third field.
Numbers, strings, and comparisons
awk treats a field as a number or a string depending on the context. A field that looks like a number compares numerically against another number, but two strings compare alphabetically. This matters when the input has values with leading zeros or with units attached. A value such as 10 is larger than 9 when compared as a number and smaller when compared as text.
printf ' 10\nb 9\n'| awk '2 > 9 { print $1 }'
printf ' x10\nb x9\n'| awk '2 > "x9" { print $1 }'The first command prints a, because 10 is greater than 9. The second prints nothing, because the text x10 sorts before x9 when both sides are strings. A quick way to force a numeric comparison is to add zero to the field, as in $2 + 0, and a quick way to force a string comparison is to concatenate an empty string.
Pattern ranges are another tool. A pattern of the form start, end selects every line from the first line that matches the start pattern through the next line that matches the end pattern. It is the awk equivalent of a sed range, and it is useful for pulling a block out of a log between two markers.
Rules run in the order they appear in the program, and every rule whose pattern matches a line runs on that line. A line can therefore trigger several rules, which is useful for counting one thing and printing another. Keep the rules short and named by their job, and put the most common cases first so that a reader sees the main path of the program at the top.
BEGIN and END
A BEGIN block runs before any input is read, which is the place to set variables or print a heading. An END block runs after the last line, which is where totals are printed. Between them, the main rules run once for every line.
awk 'EGIN { print "name" } { print $1 } END { print NR, "rows" }'people.txtThe output starts with the heading name, then the two names, then 2 rows. NR counts the records read so far, and at the END block it is the total.
Printing with control
print writes its arguments separated by OFS and ends with ORS, which is a newline by default. For columns of numbers, printf gives exact control over width and format, and it does not add a newline unless you include \n. The example prints each person right-aligned in a 6-character column.
awk ' printf "%-8s%4d\n", $1, $2 }'people.txtEach name is left-justified in eight characters and each age is right-justified in four, so the numbers line up under each other. printf is the tool to reach for whenever the output is meant to be read in columns.