/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.
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 | sortOutput
--- 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
| Syntax | Meaning |
|---|---|
| awk '{ print $1 }' file | first field of every line |
| awk -F, '...' | comma as field separator (FS) |
| $0 | the whole line |
| $NF / $(NF-1) | last / second to last field |
| NR / FNR | line number overall / in the current file |
| NF | number of fields on the line |
| -v OFS="\t" | output field separator |
Patterns
| Pattern | Selects |
|---|---|
| /error/ | lines matching a regex |
| $3 > 100 | lines where field 3 is greater than 100 |
| $1 == "north" | exact field match |
| NR > 1 | everything except the header line |
| /start/,/end/ | ranges of lines between two matches |
| BEGIN { ... } / END { ... } | run before the first / after the last line |
One-liners
| Task | Command |
|---|---|
| Count matching lines | awk '/error/ { n++ } END { print n+0 }' log |
| Unique values of a column | awk -F, '!seen[$2]++ { print $2 }' file |
| Lines longer than 80 characters | awk 'length > 80' file |
| Use a shell variable | awk -v limit="$LIMIT" '$3 > limit' file |
| Format columns | awk '{ printf "%-20s %8.2f\n", $1, $2 }' file |
Sources
Related pages
errors · sedsed: -e expression #1, char N: unterminated `s' commandGNU sed reports unterminated `s' command when a substitution misses its final delimiter, often because the pattern or replacement contains an unescaped slash.compat · sedsed -i on macOS vs Linux: GNU sed vs BSD sedGNU sed takes -i with an optional attached suffix, BSD sed on macOS needs an argument: sed -i '' on macOS, sed -i on Linux. Other GNU vs BSD sed differences.errors · findfind: paths must precede expressionfind reports paths must precede expression when an unquoted glob such as *.txt is expanded by the shell into several file names. Quote it: find . -name '*.txt'.