awk Cheat Sheet: Fields, Patterns, Arrays and One-Liners
Checked against awk GNU gawk manual, Edition 5.4 (gawk 5.4.2 tarball dated 16 Nov 2026); examples run on macOS awk 20200816 on 28 November 2026. Each section links to the official docs it was checked against.
This sheet is for developers who reach for awk when cut and grep stop being enough: pulling columns out of logs, summing a CSV, counting status codes. It follows the GNU gawk manual (Edition 5.4) and every example in the tables was run with the BWK awk that ships with macOS, version 20200816. Rows that only work in gawk are marked untested and say so.
When to use what
Use awk when each line is a record and you care about columns. If you only need to find lines, grep is faster to type; if you need to change text in place, sed is the better fit. awk earns its place the moment you want arithmetic, a running total or a count per key, because it has variables and associative arrays built in.
Keep programs on the command line short. Once a one-liner grows past two pattern-action pairs, put it in a file and run it with awk -f report.awk data.txt; you get comments, line breaks and a diff you can read.
Watch which awk you have: awk --version printed awk version 20200816 on the Mac used here, which is the BWK "one true awk", not gawk. The POSIX core (fields, NR, NF, BEGIN/END, arrays, printf, split, sub, gsub) behaves the same everywhere. gawk adds gensub(), strftime(), asort() and BEGINFILE, and those fail or silently do nothing on macOS. For structured log lines, the log parser shows the fields before you count them, and the CSV to JSON converter is easier than awk when a CSV has quoted commas.
Fields are split on runs of blanks by default. $0 is the whole line, $1 the first field, $NF the last.
awk '{ print $1 }' access.logPrint the first whitespace-separated column of every line, such as the client IP
awk '{ print $NF }' access.logPrint the last field of each line, however many fields the line has
awk -F, 'NR > 1 { print $1 }' users.csvSplit on commas and skip the header row before printing column one
awk -F, -v OFS='\t' 'NR>1 { print $1, $3 }' users.csvRead a CSV and write tab-separated output; the comma in print inserts OFS
awk 'BEGIN { FS = ","; OFS = "|" } NR>1 { $1 = $1; print }' users.csvChange the delimiter of whole lines; assigning $1 = $1 forces awk to rebuild $0 with OFS
awk '{ print NR ": " NF }' access.logShow each line number with how many fields that line split into
awk '$9 == 404' access.logPrint lines whose ninth field is 404; a pattern with no action prints the line
awk '/POST/' access.logPrint lines that match a regular expression anywhere in the line
awk '$9 ~ /^5/ { print $7 }' access.logPrint the request path for every 5xx response by matching one field against a regex
awk -F, 'NR>1 && $3 > 20 { print $1 }' users.csvCombine conditions with && to filter rows by a numeric column
awk 'NR==2, NR==3' access.logPrint a range of lines, from the first pattern match through the second
awk -v min=1000 '$10 > min { print $7, $10 }' access.logPass a shell value into the program with -v instead of splicing it into the quotes
for (k in arr) visits keys in no fixed order, so pipe to sort when order matters.
awk -F, 'NR>1 { sum += $3 } END { print sum }' users.csvTotal a numeric column and print the result once all input is read
awk '{ c[$9]++ } END { for (k in c) print k, c[k] }' access.logCount lines per HTTP status code with an associative array
awk -F, 'NR>1 { t[$2] += $3 } END { for (k in t) print k, t[k] }' users.csv | sortSum one column grouped by another, like a small GROUP BY
awk '!seen[$1]++ { print $1 }' access.logPrint each distinct first field once, keeping first-seen order
awk 'END { print NR }' access.logCount input lines, like wc -l
awk 'FNR==1 { print FILENAME }' a.txt b.txtPrint the name of each file as awk starts it; FNR resets per file while NR keeps counting
awk -F, 'NR>1 { printf "%-5s %4d\n", $1, $3 }' users.csvPrint aligned columns: left-justified name, right-justified number; printf adds no newline itself
echo 'a-b-c' | awk '{ n = split($0, p, "-"); print n, p[2] }'Split a string into an array and get back the number of pieces
echo 'hello world' | awk '{ gsub(/o/, "0"); print }'Replace every match in the line; sub() replaces only the first
echo 'Hello' | awk '{ print toupper($0), length($0), substr($0, 2, 3) }'Upper-case a string, get its length and take three characters from position 2
echo abc | gawk '{ print gensub(/b/, "X", "g") }'Return a changed copy without touching the original; gawk only, macOS awk reports an undefined function
gawk 'BEGIN { print strftime("%Y-%m-%d") }'Format the current time; a gawk extension that macOS awk does not have
Worked example: Count errors per client IP in an access log
Say you have a small access log in the common format and want to know which clients are getting 404s. Field 9 is the status and field 1 is the IP.
$ awk '$9 == 404 { c[$1]++ } END { for (ip in c) print c[ip], ip }' access.log | sort -rn
2 198.51.100.7
The pattern $9 == 404 lets only matching lines reach the action. The action bumps a counter keyed by IP. Nothing prints until END, which runs after the last line, and then sort -rn puts the noisiest client first because awk's for (k in arr) order is not defined.
Now change the question to bytes served per path, using field 10:
$ awk '{ b[$7] += $10 } END { for (p in b) printf "%6d %s\n", b[p], p }' access.log | sort -rn | head -3
4096 /blog
2560 /api/tools
128 /missing
Two requests to /api/tools (512 and 2048 bytes) were added together into 2560. That is the whole trick: pick a key field, accumulate into an array, print in END.
Common mistakes
Using double quotes around the program so the shell expands
$1before awk sees it.Wrap awk programs in single quotes and pass shell values in with
-v name=value.Setting
FSin the main block and wondering why the first line still splits on spaces.Set the separator with
-For insideBEGIN, which runs before the first record is read.Changing
OFSand expectingprint(with no arguments) to use it.Assign any field, for example
$1 = $1, so awk rebuilds the record with the new separator.Splitting a real-world CSV on commas when some values are quoted and contain commas.
Use a CSV-aware tool for that file, or gawk's
--csvoption if your gawk documents it, rather than-F,.Writing a script with
gensuborasorton Linux and shipping it to Mac users.Stick to POSIX functions in shared scripts, or call
gawkexplicitly and make it a documented dependency.
Related cheat sheets
Sources
How we research: where our facts come from, how often we re-check them, and why no one can pay for a review or a verdict.