🧮
awk cheat sheet
awk splits each line into fields ($1, $2, ... with $0 the whole line and NF the number of fields) and runs your code on lines that match. These examples work with GNU awk and most others.
Click any command to copy it.
Print columns
| Command | What it does |
|---|---|
awk '{print $1}' file | Print the first column. |
awk '{print $1, $3}' file | Print columns 1 and 3. |
awk '{print $NF}' file | Print the last column. |
awk -F: '{print $1}' /etc/passwd | Use a custom separator (here a colon). |
awk -F, -v OFS=';' '{print $1, $2}' file.csv | Read comma-separated, write semicolon-separated. |
awk '{print NR": "$0}' file | Number each line. |
awk '{$2=""; print}' file | Print everything except column 2. |
Filter rows
| Command | What it does |
|---|---|
awk 'NR==5' file | Print line 5. |
awk 'NR>=2 && NR<=4' file | Print lines 2 to 4. |
awk '/error/' file | Print lines matching a pattern. |
awk '$3 > 100' file | Print lines where column 3 is greater than 100. |
awk '$1=="alice" {print $2}' file | Print column 2 where column 1 equals alice. |
awk 'length($0) > 80' file | Print lines longer than 80 characters. |
awk 'NF' file | Skip empty lines. |
Calculate
| Command | What it does |
|---|---|
awk '{sum+=$1} END {print sum}' file | Add up column 1. |
awk '{sum+=$1} END {print sum/NR}' file | Average of column 1. |
awk 'NR==1{max=$1} $1>max{max=$1} END{print max}' file | Maximum of column 1. |
awk '{count[$1]++} END {for (k in count) print k, count[k]}' file | Count occurrences of each value in column 1. |
awk '{a[$1]+=$2} END {for (k in a) print k, a[k]}' file | Sum column 2 grouped by column 1. |
Handy one-liners
| Command | What it does |
|---|---|
awk '!seen[$0]++' file | Remove duplicate lines, keeping order. |
awk '{print toupper($0)}' file | Convert to uppercase. |
awk '{gsub(/old/,"new"); print}' file | Replace all occurrences on each line. |
awk '{print substr($0, 1, 10)}' file | Print the first 10 characters of each line. |
awk 'BEGIN {print "Header"} {print} END {print "Total:", NR}' file | Add a header and a footer. |
awk '{printf "%-10s %5d\n", $1, $2}' file | Format output in aligned columns. |
ps aux | awk '$3 > 50 {print $2, $11}' | Processes using more than 50% CPU. |
Frequently asked questions
What do NR, NF and $0 mean?
NR is the current line number, NF is the number of fields on the line and $0 is the entire line.
How do I use a variable from the shell in awk?
Pass it with -v: awk -v min=100 '$3 > min' file.