Cheatsheet: awk

Last updated 2026-06-21

Printing fields

Print the first column of a whitespace-separated file.

awk '{print $1}' file.txt

Print the second and third columns separated by the output field separator.

awk '{print $2, $3}' file.txt

Print the entire current record.

awk '{print $0}' file.txt

Print the last field on each line using NF.

awk '{print $NF}' file.txt

Print line number and line text using NR.

awk '{print NR, $0}' file.txt

Fields and separators

Use a comma as the input field separator for CSV-like data.

awk -F ',' '{print $1, $3}' data.csv

Use a regular expression field separator such as colon or comma.

awk -F '[:,]' '{print $1, $2}' file.txt

Set output field separator to a comma in a BEGIN block.

awk 'BEGIN {OFS=","} {print $1, $2, $3}' file.txt

Print the number of fields in each line using NF.

awk '{print NF}' file.txt

Skip a header row by starting after NR greater than 1.

awk 'NR > 1 {print $0}' data.tsv

Patterns and filters

Print all lines that contain a specific regular expression.

awk '/word/ {print}' file.txt

Print rows where the first field is greater than 50.

awk '$1 > 50 {print}' file.txt

Print rows matching multiple conditions with logical AND.

awk '$3 == "active" && $5 >= 100 {print $1, $5}' users.txt

Print rows matching either condition with logical OR.

awk '$2 == "error" || $2 == "warn" {print}' log.txt

Print lines between two matching patterns, inclusive.

awk '/START/,/END/ {print}' file.txt

Use next to skip comments and blank lines before other actions.

awk '/^#/ || NF == 0 {next} {print}' config.txt

Summaries and formatting

Print the sum of the first column.

awk '{sum += $1} END {print sum}' file.txt

Print the average of the first column.

awk '{sum += $1; count++} END {print sum / count}' file.txt

Print the maximum value of the first column.

awk 'NR == 1 || $1 > max {max = $1} END {print max}' file.txt

Print the minimum value of the first column.

awk 'NR == 1 || $1 < min {min = $1} END {print min}' file.txt

Count records by a field value and print totals at the end.

awk '{count[$1]++} END {for (key in count) print key, count[key]}' access.log

Use printf for aligned columns and numeric precision.

awk '{printf "%-20s %8.2f
", $1, $2}' prices.txt

Run setup and final reporting with BEGIN and END blocks.

awk 'BEGIN {print "name,total"} {sum += $2} END {print "all," sum}' data.csv

See also: