awk: Field Processing
awk is a small programming language built for columns of text. It reads input line by line, splits each line into fields, and runs your code on them. Reports from CSV files, sums of a column, reformatting command output: awk does it in one line.
Fields: $1, $2 … $NF
By default fields are separated by spaces and tabs. $1 is the first field, $2 the second, $0 the whole line, NF the number of fields and $NF the last field:
cat > sales.txt <<'TXT'
north apples 120
south pears 80
north pears 45
east apples 200
TXT
awk '{ print $2 }' sales.txt
echo "---"
awk '{ print $3, $1 }' sales.txt
echo "---"
awk '{ print NR ": " $NF " (" NF " fields)" }' sales.txtapples
pears
pears
apples
---
120 north
80 south
45 north
200 east
---
1: 120 (3 fields)
2: 80 (3 fields)
3: 45 (3 fields)
4: 200 (3 fields)
NR is the current line (record) number. In print, a comma inserts a space; strings placed next to each other are joined.
Patterns: which lines to process
An awk program is a list of pattern { action } rules. The action runs only on lines where the pattern is true:
cat > sales.txt <<'TXT'
north apples 120
south pears 80
north pears 45
east apples 200
TXT
awk '$1 == "north"' sales.txt
echo "---"
awk '$3 > 100 { print $1, $2 }' sales.txt
echo "---"
awk '/pears/ { print "pears sold in", $1 }' sales.txtnorth apples 120
north pears 45
---
north apples
east apples
---
pears sold in south
pears sold in north
A pattern without an action prints the whole line. Patterns can compare fields (==, !=, >, <), match regular expressions (/pears/, $2 ~ /^ap/) and combine with &&, ||, !.
BEGIN, END and variables
BEGIN { } runs before the first line, END { } after the last. Variables need no declaration and start as 0 or the empty string:
cat > sales.txt <<'TXT'
north apples 120
south pears 80
north pears 45
east apples 200
TXT
awk 'BEGIN { print "Total units" } { total += $3 } END { print total, "units in", NR, "rows" }' sales.txt
awk '{ sum[$1] += $3 } END { for (r in sum) print r, sum[r] }' sales.txt | sort
awk '$3 > max { max = $3; best = $0 } END { print "best:", best }' sales.txtTotal units
445 units in 4 rows
east 200
north 165
south 80
best: east apples 200
sum[$1] += $3 uses an associative array keyed by region: the classic way to group and total. for (key in array) visits keys in no particular order, hence the sort.
Separators: -F and OFS
-F sets the input field separator (a character or a regex). OFS is the output separator that print puts between comma-separated values:
cat > users.csv <<'CSV'
id,name,email,role
1,Ada,ada@example.com,admin
2,Linus,linus@example.com,dev
3,Grace,grace@example.com,dev
CSV
awk -F, 'NR > 1 { print $2 " <" $3 ">" }' users.csv
echo "---"
awk -F, -v OFS=' | ' 'NR > 1 && $4 == "dev" { print $1, $2 }' users.csv
echo "---"
awk -F: '{ print $1 }' /etc/passwd | tail -n 2Ada <ada@example.com>
Linus <linus@example.com>
Grace <grace@example.com>
---
2 | Linus
3 | Grace
---
nobody
learner
NR > 1 skips the header line. -v name=value passes a shell value into awk; it's the safe way to use a Bash variable inside an awk program.
printf and calculations
awk does floating-point maths and has C-style printf for neat reports:
cat > orders.csv <<'CSV'
item,qty,price
keyboard,2,49.90
mouse,5,19.50
monitor,1,229.00
CSV
awk -F, 'NR > 1 {
line = $2 * $3
total += line
printf "%-10s %3d x %7.2f = %8.2f\n", $1, $2, $3, line
}
END { printf "%-10s %23.2f\n", "TOTAL", total }' orders.csvkeyboard 2 x 49.90 = 99.80
mouse 5 x 19.50 = 97.50
monitor 1 x 229.00 = 229.00
TOTAL 426.30
Built-in functions include length(), substr(s, start, len), tolower(), toupper(), split(), sub(), gsub(), int() and sprintf().
Processing command output
awk shines on the output of other commands:
cat > access.log <<'LOG'
192.168.1.10 GET /index.html 200 5120
192.168.1.11 GET /missing 404 210
192.168.1.10 POST /login 302 0
192.168.1.12 GET /index.html 200 5120
192.168.1.11 GET /about.html 200 3100
LOG
awk '$4 >= 400 { errors++ } END { printf "%d of %d requests failed\n", errors, NR }' access.log
awk '{ bytes[$1] += $5 } END { for (ip in bytes) printf "%s %d\n", ip, bytes[ip] }' access.log | sort -k2 -rn
awk '{ print toupper($2), substr($3, 2) }' access.log | head -n 21 of 5 requests failed
192.168.1.12 5120
192.168.1.10 5120
192.168.1.11 3310
GET index.html
GET missing
When to use awk, sed, cut
| Task | Best tool |
|---|---|
| Replace text | sed |
| Pick fixed columns with one simple delimiter | cut |
| Columns separated by varying whitespace, calculations, conditions, grouping | awk |
| Anything bigger than a few lines of logic | Python or another full language |
Test yourself
What does $NF mean in awk?
- The number of fields
- The last field
- The line number
- The file name
Which command prints the second column of a comma-separated file?
- awk '{print $2}' f.csv
- awk -F, '{print $2}' f.csv
- awk -v 2 f.csv
- awk ',' '$2' f.csv
When does the code in an END { } block run?
- Before reading input
- After every line
- Once, after all input has been read
- Only on the last field