Processing fields with awk
- Version
- unversioned
- Review
- Draft
Summary#
awk reads input one record at a time, splits each record into fields, and runs the actions whose patterns match. $1 is the first field, NF is the field count and NR is the record number.
Syntax#
awk '{ print $1, $NF }' file
awk -F: '$3 >= 1000 { print $1 }' file
awk -v limit="$limit" '$2 > limit' file
BEGIN actions run before any input and END actions run after it.
Example#
(
set -eu
export LC_ALL=C
dir=$(mktemp -d)
trap 'rm -rf -- "$dir"' EXIT
cd "$dir"
printf '%s\n' region,amount north,120 south,80 north,30 > orders.csv
awk -F, 'NR > 1 { total[$1] += $2 }
END { for (region in total) print region, total[region] }' orders.csv | sort
min=100
echo "-- orders of at least $min"
awk -F, -v min="$min" 'NR > 1 && $2 >= min { print "line " NR ": " $0 }' orders.csv
)
Expected output#
north 150
south 80
-- orders of at least 100
line 2: north,120
Common mistakes#
The shell does not expand variables inside a single-quoted program, so pass values with -v. The order of a for (key in array) loop is unspecified; sort the output when order matters. -F, splits on every comma, including commas inside quoted CSV fields; GNU awk has a separate --csv mode for that data.
Version applicability#
The example uses standard awk features and runs with both GNU awk and mawk. The default awk in the ubuntu:26.04 container image is mawk. GNU awk added --csv in 5.3. Use gawk --csv explicitly when awk points to mawk.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0