3. AWK and the Art of Column Processing

The pattern-action language that turns text into data

sed edits text line by line. awk goes further — it splits every line into fields and gives you a tiny programming language to work with them. If you've ever needed to pull the third column from a log file, sum a column of numbers, or reformat tabular output, awk is the tool.

It was created in 1977 by Aho, Weinberger, and Kernighan — three names that show up everywhere in computer science. The language they designed is small enough to learn in an afternoon, but powerful enough that people still reach for it fifty years later.

The Core Idea: Pattern { Action }

Every awk program is a list of rules. Each rule has the form:

pattern { action }

For every line of input, awk checks each pattern. If it matches, the corresponding action runs. If you omit the pattern, the action runs on every line. If you omit the action, matching lines are printed.

Print lines containing "error"

awk '/error/' server.log

The pattern is /error/ (a regex). No action is given, so awk prints each matching line.

Fields — Automatic Column Splitting

When awk reads a line, it automatically splits it into fields separated by whitespace. The fields are numbered $1, $2, $3, etc. The entire line is $0.

Print the first and third columns

# Input: ps aux output
# USER  PID %CPU %MEM ...
awk '{ print $1, $3 }' <<<"alice 1234 2.5 1.1 /usr/bin/app"
# alice 2.5

Changing the Field Separator

By default, fields are split on whitespace. Use -F to change the delimiter:

Parse a CSV

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

Parse /etc/passwd

# Fields are colon-separated
awk -F: '{ print $1, $7 }' /etc/passwd
# root /bin/bash
# nobody /usr/bin/nologin
# ...

You can also set the separator inside the program using the FS variable:

awk 'BEGIN { FS = ":" } { print $1, $7 }' /etc/passwd

BEGIN and END

Two special patterns run at specific times:

  • BEGIN — runs once before any input is read
  • END — runs once after all input is processed

These are perfect for setup and summary:

Sum a column of numbers

# expenses.txt:
# rent 1200
# food 400
# utils 150

awk '{ total += $2 } END { print "Total:", total }' expenses.txt

Total: 1750

Print a header and footer

awk 'BEGIN { print "Name", "Shell" }
     { print $1, $7 }
     END { print "---"; print NR, "users" }' /etc/passwd

Built-in Variables

awk tracks several useful values automatically:

Variable Meaning
NR Current line number (across all files)
NF Number of fields on the current line
FS Input field separator (default: whitespace)
OFS Output field separator (default: space)
RS Input record separator (default: newline)
ORS Output record separator (default: newline)
FILENAME Name of the current input file

Number every line

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

Print lines with more than 5 fields

awk 'NF > 5' data.txt

Patterns in Depth

Patterns can be much more than regular expressions:

Pattern Matches
/regex/ Lines matching the regex
$3 > 100 Lines where the third field exceeds 100
NR == 1 The first line only
NR > 1 Every line except the first
/start/,/end/ Range: from a line matching /start/ to one matching /end/
BEGIN Before any input
END After all input

Print processes using more than 10% CPU

ps aux | awk 'NR > 1 && $3 > 10.0 { print $1, $11, $3 "%" }'

Operators and Expressions

awk supports the arithmetic and string operations you'd expect:

Arithmetic

{ total += $2 }          # addition
{ avg = total / NR }     # division
{ pct = ($3 / $2) * 100 } # percentage

String Concatenation

In awk, strings concatenate by being placed next to each other — no operator needed:

{ fullname = $1 " " $2 }

Comparison and Logic

$3 > 100 && $4 != "skip"   # AND
$1 == "root" || $1 == "admin"  # OR
$5 !~ /test/               # regex negation

Control Flow

awk has the usual control structures:

# if/else
{
    if ($3 > 90)
        print $1, "excellent"
    else if ($3 > 70)
        print $1, "good"
    else
        print $1, "needs work"
}
# for loop — print fields in reverse
{
    for (i = NF; i >= 1; i--)
        printf "%s ", $i
    print ""
}
# while loop
{
    i = 1
    while (i <= NF) {
        if ($i ~ /error/) print "Field", i, "has error"
        i++
    }
}

Associative Arrays

One of awk's most powerful features is its associative arrays — arrays indexed by strings, not just numbers. This makes counting and grouping trivial.

Count occurrences of each HTTP status code

# access.log fields: IP - - [date] "method path" status size
awk '{ count[$9]++ } END { for (code in count) print code, count[code] }' access.log
# 200 4523
# 404 87
# 500 12

Sum bytes transferred per IP

awk '{ bytes[$1] += $10 } END { for (ip in bytes) print ip, bytes[ip] }' access.log

Checking for Membership

Use in to test whether a key exists:

if ("404" in count) print "Got some 404s"

Deleting Elements

delete count["200"]

Built-in Functions

String Functions

Function What it does
length(s) Length of string s
substr(s, start, len) Substring extraction
index(s, target) Position of target in s (1-based)
split(s, arr, sep) Split s into array arr on separator sep
sub(regex, repl, s) Replace first match in s
gsub(regex, repl, s) Replace all matches in s
tolower(s) Lowercase
toupper(s) Uppercase
match(s, regex) Returns position of regex match (sets RSTART, RLENGTH)
sprintf(fmt, ...) Formatted string (like C sprintf)

Extract a date from a log line

# Line: [2026-04-15 08:32:01] INFO Starting server
awk '{ print substr($1, 2, 10) }' app.log
# 2026-04-15

Math Functions

Function What it does
int(x) Truncate to integer
sqrt(x) Square root
sin(x), cos(x) Trigonometric functions
log(x) Natural logarithm
exp(x) e^x
rand() Random number between 0 and 1
srand(seed) Seed the random number generator

printf — Formatted Output

print adds spaces between arguments and a newline at the end. For precise control, use printf:

awk '{ printf "%-20s %8.2f\n", $1, $2 }' prices.txt
# apples                  3.50
# bananas                 1.25

Common format specifiers: %s (string), %d (integer), %f (float), %x (hex). Width and alignment work like C's printf.

Practical Recipes

Deduplicate lines (preserving order)

awk '!seen[$0]++' file.txt

This is one of awk's most famous one-liners. The first time a line appears, seen[$0] is 0 (false after !... wait — !0 is true), so it prints. After incrementing, subsequent duplicates evaluate to false.

Transpose rows and columns

awk '{
    for (i = 1; i <= NF; i++)
        a[i] = (a[i] ? a[i] OFS : "") $i
}
END {
    for (i = 1; i <= length(a); i++)
        print a[i]
}' matrix.txt

Quick CSV to TSV

awk -F',' -v OFS='\t' '{ $1=$1; print }' data.csv

The $1=$1 trick forces awk to reconstruct the line using OFS.

Top 10 most common words

awk '{ for (i=1; i<=NF; i++) words[tolower($i)]++ }
     END { for (w in words) print words[w], w }' file.txt | sort -rn | head -10

Running average

awk '{ sum += $1; print $1, sum/NR }' numbers.txt

Multiple Rules

You can have as many pattern-action pairs as you want. They all execute (in order) on each line:

/error/   { errors++ }
/warning/ { warnings++ }
END       { print errors, "errors,", warnings, "warnings" }

When to Use AWK vs. Other Tools

Task Best tool
Simple find-and-replace sed
Column extraction and arithmetic awk
JSON processing jq
Complex data pipelines Python, Perl
Quick line filtering grep

awk sits in a sweet spot: more powerful than sed and grep, simpler than a full scripting language. When your task is "split lines into fields and do something with them," awk is almost always the right answer.

Summary

  • awk splits every line into fields ($1, $2, ..., $NF)
  • Programs are pattern { action } rules — patterns select lines, actions process them
  • BEGIN and END handle setup and summary
  • Associative arrays make counting and grouping effortless
  • Built-in variables like NR, NF, and FS track input state automatically
  • printf gives you precise output formatting
  • For column-oriented text processing, awk remains the fastest path from problem to solution