awk: Fields, Records and Reports

awk: Fields, Records and Reports in Bash: --- At the gate of a quarry stands a weighbridge, and beside it sits a tally clerk.


The Analogy: The Tally Clerk at the Weighbridge

At the gate of a quarry stands a weighbridge, and beside it sits a tally clerk. All day, trucks roll across the plate one at a time, and with each truck the driver hands over a docket: a single line of print with the load's details spaced out in columns -- haulier, product code, gross weight, price per tonne. The clerk deals with exactly one docket at a time, reads the columns they care about, jots something in a ledger, and waves the truck on. The whole day's accounting is this one motion repeated for every truck: read a line, act on its columns, move to the next.

The clerk does not read the docket as a sentence; they read it as positions. "Column three is the weight, column four is the price." They never care that the docket is text -- they care that the third thing along is a number they can multiply by the fourth. This is the heart of the clerk's skill and the heart of awk: every incoming line is automatically split into numbered fields, and the clerk refers to them by position -- the first field, the third field, the last field -- rather than by hunting through the text.

Before the first truck arrives, the clerk rules up a fresh ledger page with column headings; that is a one-time setup done at the start of the shift. Through the day they keep running subtotals -- a tally of tonnes per product code, kept in labelled boxes down the side of the ledger, each box growing as matching trucks cross. Then, after the last truck has gone, the clerk turns to a clean sheet and writes the summary: total tonnes, revenue per product, the day's grand total. The three phases -- rule up once, tally each truck, summarise at the end -- are exactly awk's BEGIN block, its per-line rules, and its END block.

The clerk's method has one fragile assumption: that the columns line up. The docket is split on spaces, so a haulier called "North East Haulage" -- three words with spaces -- is read as three separate columns, and every column after it shifts one place to the right. Now "column three" is no longer the weight; the clerk multiplies the wrong things and the ledger fills with quiet nonsense, never an error, just wrong totals. The lesson the clerk learns the hard way is that position-based reading is only as reliable as the spacing of the source, and that a field which can contain the separator will eventually wreck the count.


Syntax or Core Structure

awk reads input one line at a time, splits each line into fields on whitespace, and runs a program of the form pattern { action } against every line. Inside the action, $1 is the first field, $2 the second, and $0 the whole line. The simplest useful program prints one column:

# sales.txt: region product units price
north widget 4 25
south gadget 2 40
north gadget 5 40
east widget 3 25
north widget 1 25
awk '{ print $2 }' sales.txt

Output:

widget
gadget
gadget
widget
widget

With no pattern before the braces, the action runs on every line, so this prints the product column. Fields are more than text: awk treats them as numbers when you do arithmetic, so $3 * $4 multiplies units by price. Printing the region alongside that product of two columns gives a per-line revenue:

awk '{ print $1, $3 * $4 }' sales.txt

Output:

north 100
south 80
north 200
east 75
north 25

The comma in print $1, $3 * $4 inserts a space between the two values. awk did the splitting, the field numbering, and the arithmetic without a single line of setup: that terseness for columnar data is exactly why it exists.


Technical Depth: Patterns, Built-in Variables and Totals

Patterns select which lines an action runs on

A pattern before the braces is a condition; the action runs only on lines that satisfy it. The pattern can compare a field, match a regular expression, or test a built-in variable. To see only the northern sales:

awk '$1 == "north" { print }' sales.txt

Output:

north widget 4 25
north gadget 5 40
north widget 1 25

$1 == "north" is the pattern; { print } with no argument prints the whole line, the same as print $0. A bare regular expression such as /widget/ matches lines containing that text, and a comparison like $3 > 3 selects by a numeric field. Pattern and action are independent: either can be omitted, and awk supplies a sensible default for the missing half.

Built-in variables

awk maintains several variables for every line automatically. These are the ones you reach for constantly:

VariableMeaning
$0The entire current line
$1 ... $NFThe first through last fields
NFNumber of fields on this line
NRRecord number, i.e. the line count so far
FSInput field separator (default: whitespace)
OFSOutput field separator used by print (default: space)

Printing NR and NF alongside the line is the fastest way to see how awk has parsed your data:

awk '{ print NR, NF, $0 }' sales.txt

Output:

1 4 north widget 4 25
2 4 south gadget 2 40
3 4 north gadget 5 40
4 4 east widget 3 25
5 4 north widget 1 25

Every line here has four fields; if one showed 3 or 5, you would know the spacing had gone wrong before it corrupted a total.

BEGIN, END and running totals

A pattern of BEGIN runs once before any line is read, and END runs once after the last line. END is where summaries belong, because by then every line has contributed to the totals you accumulated along the way:

awk '{ total += $3 * $4 } END { print "revenue", total }' sales.txt

Output:

revenue 480

The variable total starts empty (treated as zero), grows by each line's revenue, and is printed only in END. To break the total down by group, use an associative array indexed by a field. Because array iteration order is unspecified, pipe the result through sort for stable output:

awk '{ rev[$1] += $3 * $4 } END { for (r in rev) print r, rev[r] }' sales.txt | LC_ALL=C sort

Output:

east 75
north 325
south 80

rev[$1] keeps one running subtotal per region -- the labelled boxes down the side of the ledger -- and the END loop prints each. The LC_ALL=C sort is not cosmetic: without it the three lines could appear in any order from run to run, which would make the output impossible to compare or test.

Counting and averaging per group

An associative array can hold more than one running figure per key. Keeping both a subtotal and a count lets END report an average, which is a tally the weighbridge clerk could never do until the last truck had crossed:

awk '{ rev[$1] += $3 * $4; n[$1]++ }
     END { for (r in rev) printf "%-6s count=%d avg=%.2f\n", r, n[r], rev[r] / n[r] }' sales.txt | LC_ALL=C sort

Output:

east   count=1 avg=75.00
north  count=3 avg=108.33
south  count=1 avg=80.00

n[$1]++ counts the lines per region while rev[$1] sums their revenue, and rev[r] / n[r] in END divides the two. North's three sales average 108.33; the single-sale regions average their only value. As before, the output is sorted so the three lines never reorder.

NR versus FNR across files

When awk reads several files at once, NR keeps counting across all of them while FNR restarts at each new file. FILENAME names the current file. Seeing all three together makes the difference concrete:

awk '{ print FILENAME, FNR, NR, $0 }' f1.txt f2.txt

Output:

f1.txt 1 1 a
f1.txt 2 2 b
f2.txt 1 3 c
f2.txt 2 4 d

At the first line of f2.txt, FNR is back to 1 but NR has reached 3. Use FNR for "which line of this file" and NR for "how many lines in total"; mixing them up is a common source of off-by-one bugs when processing a directory of files.

Separators and formatting

The input separator is not always whitespace. -F: splits on colons, which parses colon-delimited files like /etc/passwd. And printf gives column-aligned output where print gives ragged output:

awk '{ printf "%-8s %6.2f\n", $2, $3 * $4 }' sales.txt

Output:

widget   100.00
gadget    80.00
gadget   200.00
widget    75.00
widget    25.00

%-8s left-justifies the product in an eight-wide column and %6.2f right-justifies the revenue to two decimals, so the numbers line up as a real report rather than space-separated values.


Real World Example: A Per-Region Sales Report

The task is a daily summary from sales.txt: for each region, total the units and the revenue, then print a grand total across all regions. This revenue_report.sh uses an associative array for the per-region tallies, sorts the detail for stable output, and computes the grand total in a second pass so it always lands at the foot of the report.

#!/usr/bin/env bash
# revenue_report.sh -- per-region sales summary with a grand total
set -euo pipefail

FILE="${1:-sales.txt}"

# Per-region detail, sorted for stable output
awk '{ rev[$1] += $3 * $4; units[$1] += $3 }
     END { for (r in rev)
              printf "%-6s units=%-3d revenue=%d\n", r, units[r], rev[r] }' "$FILE" \
  | LC_ALL=C sort

# Grand total on a second pass so the sorted block stays clean
awk '{ g += $3 * $4 } END { printf "TOTAL  revenue=%d\n", g }' "$FILE"

Running bash revenue_report.sh prints:

Output:

east   units=3   revenue=75
north  units=10  revenue=325
south  units=2   revenue=80
TOTAL  revenue=480

The first awk does the real work: for every line it adds the line's revenue to rev[$1] and its units to units[$1], both indexed by region. In END it walks those arrays and prints one printf line per region. Piping that block through LC_ALL=C sort turns awk's unordered array walk into a fixed east-north-south order, so the report is identical every run. The second awk re-reads the file for a single grand total, kept separate so it cannot be swept into the sorted region lines.

Splitting the work into two passes is a deliberate readability choice: it keeps the sorted detail and the unsorted total from fighting over the same pipe. The per-region arrays scale to any number of regions without code changes, and printf gives the report aligned columns that a spreadsheet or a reviewer can scan at a glance. For a file of this size the double read costs nothing measurable.

That two-pass design is also the script's real limitation. It assumes the input is a re-readable file: feed it from a pipe with FILE=/dev/stdin and the first awk drains the stream, leaving the second pass with nothing and a grand total of zero -- a silently wrong report rather than an error. The deeper fragility is the one from the analogy: fields are split on whitespace, so a region named north east becomes two fields, shifting units and price one place right and computing widget * 4, which awk reads as 0. Both faults are quiet. A robust version would total in a single pass and read a delimiter that cannot appear inside a field, such as a tab, set with -F'\t'.


Common Mistakes

  1. Assuming fields never contain the separator. With default whitespace splitting, a value like north east becomes two fields and every later field shifts right. Choose a delimiter that cannot appear in the data, such as a tab, for anything but the simplest input.
  1. Writing $ in front of awk variables. In awk, $ means "the field numbered by", so $total is the field whose number is the value of total, almost never what you want. Plain variables are just total, rev, count; only fields use $.
  1. Confusing = with == in a pattern. $1 = "north" assigns to field one and matches every line; $1 == "north" compares. The single-equals bug silently rewrites your data and selects everything.
  1. Relying on array iteration order. for (k in arr) visits keys in an unspecified order that can change between runs. Pipe the output through sort, or collect and sort keys, whenever the order matters.
  1. Comparing numbers as strings. If a field is treated as a string, "10" < "9" is true because it compares character by character. Force numeric context (for example $3 + 0 < 9) when a field could be compared the wrong way.
  1. Trying to expand a shell variable inside single quotes. The awk program is single-quoted, so $var from the shell will not expand inside it. Pass values in with -v name=value and use name in the program.
  1. Expecting OFS to reformat $0 automatically. Changing OFS only affects print with a comma list; to re-space the whole line you must assign to a field first (for example $1 = $1) to force awk to rebuild $0.
  1. Forgetting the newline in printf. awk's printf does not add a trailing newline, so printf "%s", $1 runs every value together on one line. Include \n explicitly.
  1. Mixing up NR and FNR across files. NR counts all records seen; FNR resets per file. Using NR when you meant "line number within this file" breaks multi-file processing.

Best Practices

  • Set the field separator explicitly for structured data. Use -F'\t' or a BEGIN { FS = "," } so parsing does not depend on fragile whitespace alignment.
  • Pass shell values in with -v. Keep the program single-quoted and inject variables as awk -v limit="$n" '...', rather than breaking the quotes to interpolate.
  • Sort any array-driven output. Pipe END-block loops through LC_ALL=C sort so a report built from an associative array is reproducible.
  • Prefer printf for reports. Aligned columns from printf are far easier to read and diff than the ragged output of print with commas.
  • Total in a single pass when you can. One pass avoids re-reading the input, which matters the moment the source is a pipe rather than a seekable file.
  • Check NF when layout matters. A quick NF != 4 { ... } guard catches malformed lines before they poison a total.
  • Force numeric context for numeric comparisons. Add zero or compare against a number so a field is not accidentally compared as a string.
  • Know awk's limits. For quoted CSV with embedded separators, use a CSV-aware tool; awk's simple splitting cannot honour quoting rules.

Practice Exercises

  1. Per-product revenue. Using sales.txt, write an awk program that totals revenue per product (not region) and prints each product with its total, piped through sort for stable order. Verify the two product totals by hand.
  1. Filter then count. Write a program that prints only lines where units ($3) is at least 4, and in END prints how many such lines there were. Confirm the count against the file.
  1. Inject a threshold. Rewrite the previous exercise so the threshold comes from the shell via awk -v min="$n", and run it with two different values of n. Explain why -v is needed instead of $n inside the program.
  1. Break and fix the split. Add a line whose region is north east to sales.txt and show that its revenue is computed as 0. Then convert the file to tab-separated, parse it with -F'\t', and show the region is now read whole.