December 5, 2026

awk Examples: Printing Columns, Filtering Rows, Summing, and the Comparisons That Go Wrong

A printed spreadsheet with one column highlighted under a yellow ruler

awk '{print $1, $3}' is the single most useful line of awk, and most people stop there. The same tool, without leaving the command line, filters rows by any column, sums and averages, groups totals by key, and reformats output. It also has two habits that bite: a comma-separated file with a quoted comma in it, and a comparison that silently switches from numbers to text. Every example below was run on Ubuntu, where awk is mawk 1.3.4, and the output shown is what it printed. The rules come from the POSIX specification, so they apply to gawk and BSD awk as well.

Video: DistroTube on YouTube

Fields and records

How awk splits a line

awk reads input one record at a time, normally one line, and splits it into fields $1, $2 and so on; $0 is the whole line. The splitting rule is the first thing worth knowing. The POSIX specification says that when the field separator is the default single space, awk will skip leading and trailing blank and newline characters, and fields are delimited by sets of one or more blanks. Any other single character separates on each occurrence.

That is why the default works on messy, space-aligned output. A test file:

name  dept   salary
ana   eng    95000
ben   ops    72000
cy    eng    88000
dee   sales  64000

awk '{print $1, $3}' staff.txt printed name salary, ana 95000 and so on, ignoring the runs of spaces. Forcing a single-space separator instead with -F'[ ]' on the line a b made the second field empty: two spaces now meant an empty field between them.

NR and NF

Two built-in variables do most of the bookkeeping. The specification defines NR as the ordinal number of the current record; inside an END block it holds the number of the last record processed. NF is the number of fields on the current line, so $NF is always the last column:

$ awk 'NR>1 {print $NF}' staff.txt
95000
72000
...
$ awk 'END {print NR}' access.log
4

NR>1 is the standard way to skip a header line, and END {print NR} is a line counter.

Spreadsheet on a screen

Filtering rows

Patterns in front of actions

An awk program is a list of pattern {action} pairs. A row that matches the pattern runs the action; with no action, the default is to print the line.

$ awk '$2=="eng" {print $1}' staff.txt
ana
cy
$ awk 'NR>1 && $3>80000' staff.txt
ana   eng    95000
cy    eng    88000

The second example has no action at all, so matching lines print whole. That one line replaces a pipeline of grep and cut, and unlike grep, it tests a specific column instead of the whole line. The earlier posts on grep regex and sed cover the line-oriented tools; awk is the one that knows about columns.

Passing shell variables in

Values from the shell should go in through -v, not by pasting them into the quoted program:

$ min=80000
$ awk -v m="$min" 'NR>1 && $3>m {print $1}' staff.txt
ana
cy

The specification notes that such an assignment is treated as a numeric string when it looks like a number, so m compares numerically, as intended.

Totals, averages and group-by

Accumulating in variables

Variables in awk start empty and become zero when used as numbers, so totals need no setup:

$ awk 'NR>1 {s+=$3; n++} END {print s, s/n}' staff.txt
319000 79750

Associative arrays

Arrays indexed by strings give a one-line group-by:

$ awk 'NR>1 {t[$2]+=$3} END {for (d in t) print d, t[d]}' staff.txt | sort
eng 183000
ops 72000
sales 64000

The sort is there because for (d in t) visits keys in no particular order. The same shape counts things. A test web log:

2026-05-01 GET /index.html 200 512
2026-05-01 GET /missing 404 0
2026-05-02 POST /api 500 87
2026-05-02 GET /index.html 200 512

awk '{c[$4]++} END {for (s in c) print s, c[s]}' access.log | sort printed 200 2, 404 1, 500 1: a status-code report in one line.

Pill organizer with compartments

Regular expressions, ranges and text functions

Matching a field against a pattern

~ tests a field against a regular expression, which grep cannot do for one column. On the test log, awk '$3 ~ /^\/index/ {print $1}' access.log printed the dates of the two requests for /index.html and nothing else.

Ranges between two patterns

A pattern pair separated by a comma selects every line from a match of the first through a match of the second. On a small INI-style file:

header
[db]
host=a
port=5432
[cache]
host=b

awk '/^\[db\]/,/^\[cache\]/' conf.ini printed the [db] block, including both marker lines. Ranges include their endpoints. When only the body of a section is wanted, a flag works better: awk '/^\[/{s=($0=="[db]")} s && !/^\[/' conf.ini printed exactly host=a and port=5432.

Built-in string functions

awk carries a small string toolkit. gsub replaces every match and returns how many it made: on 2026-05-01, gsub(/-/,"/") produced 2026/05/01 and returned 2. split breaks a string into an array and returns the count: the same date split on - gave 3 pieces, with 2026 first and 01 last. substr and toupper turned x9m8 blog into X9.

Removing duplicate lines, in order

One idiom deserves its own line. awk '!seen[$0]++' prints each line the first time it appears and never again, keeping the original order. Fed b a b c a, one per line, it printed b a c. sort -u would have reordered them.

awk or cut

cut -d' ' -f2 on the line ana eng, with three spaces, printed an empty line: cut treats every space as a separator, so field 2 is the empty string between the first two spaces. awk '{print $2}' printed eng, because of the default splitting rule described at the top. For anything aligned with spaces, awk is the safer column picker. It is not slow either: summing a 2-million-line file of numbers took 0.17 seconds in the test.

Formatting output

printf

print separates its arguments with the output field separator, a space by default. For aligned columns, printf takes C-style formats:

$ awk 'NR>1 {printf "%-5s %8.2f\n", $1, $3/12}' staff.txt
ana    7916.67
ben    6000.00
cy     7333.33
dee    5333.33

Changing the separator

Setting OFS changes what goes between fields on output, but only for lines awk rebuilds. Assigning a field to itself forces the rebuild:

$ awk 'BEGIN{OFS=","} NR>1 {$1=$1; print}' staff.txt
ana,eng,95000
ben,ops,72000

Without $1=$1, print writes the original line unchanged, spaces and all. The same rebuilding happens when a field past the end is assigned: on the line a b c, NF was 3; after $5="e", it was 5, and the line printed as a b c e, with an empty fourth field in between.

Blue and white note with numbers

Where awk goes wrong

Quoted commas in CSV

-F, splits on every comma. It knows nothing about quotes. On the line:

ana,eng,"Smith, Jr",95000

awk -F, '{print $3}' printed "Smith, half a field with a stray quote. For this particular line, splitting on the quote character instead with -F'"' and printing $2 returned Smith, Jr, but that trick breaks as soon as a line has two quoted fields or an escaped quote. Real CSV needs a CSV parser; newer gawk releases have a CSV mode, and tools such as Python’s csv module handle it properly.

Numbers that are not numbers

awk decides whether to compare as numbers or as text based on what the values look like. The specification says a numeric comparison is made when both operands are numeric or numeric strings; otherwise, operands shall be converted to strings and compared as strings.

The test made it visible. On the line 10 9, $1>$2 printed 1: ten is greater than nine. On the line 10 9x, the same comparison printed 0. 9x is not a numeric string, so awk compared the text "10" with "9x", and as text, 1 sorts before 9. Nothing warned about it.

The same specification suggests the fix: force the type you mean, by adding zero to make a number or concatenating an empty string to make a string. $2+0 turns 9x into 9, and $1>$2+0 printed 1 again. In the other direction, on the line 05 5, $1==$2 printed 1 (five equals five), while $1""==$2"" printed 0 (the strings differ). When a column might contain units, stray characters or leading zeros, writing +0 or "" makes the comparison say what it means.

Programs in a file, and one-liners worth keeping

When the one-liner grows

Past a line or two, an awk program reads better from a file run with awk -f. A small report, saved as report.awk:

BEGIN { printf "%-6s %10s\n", "dept", "total" }
NR > 1 { total[$2] += $3; n++ }
END {
  for (d in total) printf "%-6s %10d\n", d, total[d]
  printf "%-6s %10d\n", "all", n
}

awk -f report.awk staff.txt printed a header line from the BEGIN block, one line per department with its total, and a final all 4 line counting the employees. BEGIN runs before any input is read, which makes it the place for headers and for setting FS or OFS; END runs after the last line, where totals are known. The department lines happened to come out in alphabetical order in this run, but for (d in total) makes no such promise, so a report that must be ordered should pipe its body through sort or build its own order.

From the tests above

  • Columns: awk '{print $1, $3}'
  • Last column: awk '{print $NF}'
  • Skip a header: awk 'NR>1'
  • Rows where a column matches: awk '$2=="eng"'
  • Sum a column: awk '{s+=$3} END {print s}'
  • Count by key: awk '{c[$4]++} END {for (k in c) print k, c[k]}'
  • Comma-separated output: awk 'BEGIN{OFS=","} {$1=$1; print}'
  • Numeric comparison, forced: awk '$3+0 > 100'

Sources

  • awk, The Open Group Base Specifications Issue 8 (POSIX.1-2024): https://pubs.opengroup.org/onlinepubs/9799919799/utilities/awk.html

719 Posts

Peter Kalafatis writes and edits X9M8. He holds a bachelor's degree from LIU Post and a master's in Media Studies from The New School, with academic work in the philosophy of science, human behavior, AI, and memetics.

View All Posts

Leave a Reply

Your email address will not be published. Required fields are marked *