awk Cheatsheet - Linux Text Processing Reference
awk's killer use case is column-based aggregation: computing response-code proportions from an nginx log or summing and grouping a report is much faster than writing a script. Understanding RS/FS, NR/NF, and how variables print covers about eighty percent of awk.
Basic Syntax 6
awk '{print $1}' filePrint the first column (space-separated by default)
awk -F: '{print $1, $3}' /etc/passwdUse colon as the field separator
awk '{print $1, $NF}' filePrint first and last column
awk '{print NR, $0}' filePrint line number and whole line
awk 'NR==10' filePrint line 10
awk 'NR>=10 && NR<=20' filePrint lines 10-20
Built-in Variables 8
$0The whole line
$1, $2, $NF1st / 2nd / last column
NRCurrent line number (global)
NFNumber of columns in the current line
FSInput field separator (space by default)
OFSOutput field separator
RSInput record separator (newline by default)
ORSOutput record separator
Conditionals 6
awk '$3 > 100' filePrint lines where column 3 > 100
awk '$1 == \"error\"' filePrint lines where column 1 equals 'error'
awk '$1 ~ /pattern/' fileColumn 1 matches a regex
awk '$1 !~ /pattern/' fileColumn 1 does not match a regex
awk 'NR==1 || $1 > 100' fileFirst line or column 1 > 100
awk '$1 == \"a\" {print $2}' fileCondition with action
Statistics 5
awk '{sum += $1} END {print sum}' fileSum column 1
awk '{sum += $1} END {print sum/NR}' fileAverage of column 1
awk '{count++} END {print count}' fileCount lines
awk '{count[$1]++} END {for(k in count) print k, count[k]}' fileGroup and count by column 1
awk 'BEGIN{max=0} {if($1>max) max=$1} END{print max}' fileFind the max of column 1
String Functions 7
length($0)Length of the current line
substr($0, 5, 10)Substring from char 5, length 10
index($0, \"text\")Find substring position (1-based; 0 if not found)
split($0, arr, \":\")Split into an array by a delimiter
sub(/old/, \"new\", $0)Replace first match
gsub(/old/, \"new\", $0)Replace all matches
tolower($0) / toupper($0)Convert to lower/upper case
Common Patterns 5
awk '{print $1}' access.log | sort | uniq -c | sort -rnTop IPs by access count
awk '$9 == 500 {print $7}' access.logExtract URLs with 500 errors
awk -F, '{print $2, $3}' data.csvProcess a CSV file
awk 'BEGIN{OFS=\",\"} {print $1, $2}' fileOutput as CSV
awk '{sum+=$5} END{print sum/1024/1024 \" MB\"}' fileSum a column and convert units
Tips
- awk splits on whitespace or tabs by default; use -F to specify another separator.
- The BEGIN block runs before processing, the END block runs after.
- awk arrays are associative (hash tables); keys can be strings.
Official References
Each command links to its official documentation below, so you can verify the latest usage and read deeper.
Maintained by LaoHand
Publicly updated on Jul 21, 2026, continuously proofread against official docs.
Contact Us
Wrong command or description? Send us corrections, business inquiries or product feedback by email.
Contact Us