Skip to content

/cheatsheets/awk/awk-cheat-sheet

awk cheat sheet: fields, patterns, sums and printf

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · GNU Awk 5.4.1updated 2026-10-20
tool
awk
versions
GNU awk 5.x, POSIX awk
os
linux, macos, windows

awk reads input line by line, splits each line into fields ($1, $2, … $NF) and runs pattern { action } rules. The examples below all use the same small CSV file.

bash
cat > sales.csv <<'EOF'
region,product,units,price
north,apple,10,0.5
south,pear,4,0.75
north,pear,7,0.75
east,apple,12,0.5
EOF
echo "--- columns 1 and 3:"; awk -F, 'NR > 1 { print $1, $3 }' sales.csv
echo "--- rows where units > 6:"; awk -F, 'NR > 1 && $3 > 6' sales.csv
echo "--- total units:"; awk -F, 'NR > 1 { sum += $3 } END { print sum }' sales.csv
echo "--- revenue per region:"; awk -F, 'NR > 1 { r[$1] += $3 * $4 } END { for (k in r) printf "%-6s %6.2f\n", k, r[k] }' sales.csv | sort

Output

--- columns 1 and 3:
north 10
south 4
north 7
east 12
--- rows where units > 6:
north,apple,10,0.5
north,pear,7,0.75
east,apple,12,0.5
--- total units:
33
--- revenue per region:
east     6.00
north   10.25
south    3.00

Basics

SyntaxMeaning
awk '{ print $1 }' filefirst field of every line
awk -F, '...'comma as field separator (FS)
$0the whole line
$NF / $(NF-1)last / second to last field
NR / FNRline number overall / in the current file
NFnumber of fields on the line
-v OFS="\t"output field separator

Patterns

PatternSelects
/error/lines matching a regex
$3 > 100lines where field 3 is greater than 100
$1 == "north"exact field match
NR > 1everything except the header line
/start/,/end/ranges of lines between two matches
BEGIN { ... } / END { ... }run before the first / after the last line

One-liners

TaskCommand
Count matching linesawk '/error/ { n++ } END { print n+0 }' log
Unique values of a columnawk -F, '!seen[$2]++ { print $2 }' file
Lines longer than 80 charactersawk 'length > 80' file
Use a shell variableawk -v limit="$LIMIT" '$3 > limit' file
Format columnsawk '{ printf "%-20s %8.2f\n", $1, $2 }' file

Sources