Learn / Linux / Text Processing
Lesson 14 of 74

Working with Columns: awk

awk as a small language for column-based text: how it splits lines into fields, pattern-action rules, built-in variables (NR, NF, FS, OFS), comparisons and regex, variables and calculations, BEGIN and END, arrays for grouping, printf formatting, and the awk one-liners DevOps engineers use daily.

30 min read Report a problem Hands-on lab included 6-question quiz

What awk is

awk is a small programming language built for one job: reading text that's arranged in columns and doing something with those columns. It's named after its three creators at Bell Labs (Aho, Weinberger and Kernighan) and has been on every Unix system since 1977.

Where grep finds lines and cut takes columns, awk can do both at once, and make decisions, calculate totals and averages, group values and format reports, all in one command. For a DevOps engineer it fills the gap between a one-liner and a full script.

How awk reads input

awk splits every line into fields

input lineweb-01 prod running 4 8
split
$1web-01
$2prod
$3running
$44
$5 = $NF8 (the last field)

$0 is the whole line. NF = 5 (number of fields). NR = the line number.

For each line, awk:

  1. reads it into $0,
  2. splits it into fields $1, $2, ... (by default on runs of spaces or tabs, ignoring spaces at the start),
  3. runs your program on it,
  4. moves to the next line.

That default splitting is why awk handles aligned output (ps, df, ls -l, kubectl get) that breaks cut.

Pattern { action }

An awk program is a list of rules:

text
awk 'PATTERN { ACTION }' file
  • If the pattern is true for a line, the action runs.
  • No pattern: the action runs on every line.
  • No action: matching lines are printed whole.
ProgramDoes
awk '{print $1}'print field 1 of every line
awk '$3 == "running"'print lines whose field 3 is "running"
awk '/ERROR/ {print $2}'for lines matching the regex ERROR, print field 2
awk 'NR > 1 {print $1}'skip the header, print field 1

Always wrap the program in single quotes, otherwise the shell replaces $1 with its own (empty) variable.

Printing fields

bash
awk '{print $1, $3}' inventory.txt | head -3
awk '{print $NF}' df.txt
text
HOST STATUS
web-01 running
web-02 running
text
on
/
/var/lib/docker
...

In print, a comma inserts a space (the output separator) between values. Without a comma, values are glued together: print $1 $3 gives web-01running. $NF is the last field of each line, whatever the number of columns.

ExpressionValue
$1, $2, ...field 1, 2, ...
$0the whole line
$NFthe last field
$(NF-1)the second-to-last field
NFhow many fields this line has
NRthe line number (across all files)
FNRthe line number within the current file
FILENAMEthe name of the current file
text
awk '{print NR": "$0}' file        # number every line
awk 'NF > 0' file                  # drop empty lines (they have 0 fields)
awk 'END {print NR}' file          # count lines, like wc -l

Choosing the separator: -F, FS and OFS

For files with a fixed delimiter, set the input field separator:

CommandSplits on
awk -F, '...'commas (CSV)
awk -F: '...'colons (/etc/passwd)
awk -F'\t' '...'tabs
awk -F'[,;]' '...'a regex: comma or semicolon
bash
awk -F: '{print $1, $6}' /etc/passwd | tail -3
text
asha /home/asha
vikram /home/vikram
meera /home/meera

Inside the program, the same settings are the variables FS (input separator) and OFS (output separator), usually set in a BEGIN block:

text
$ awk 'BEGIN {FS=","; OFS=" | "} NR > 1 {print $1, $2, $4}' sales.csv | head -3
north | laptop | 840000
south | phone | 1200000
west | laptop | 490000
Try it · Task 1 of 4

Fields and separators

List the real user accounts with their home folders.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

By default awk splits each line on runs of spaces or tabs, so it handles aligned columns (like ps, df or this inventory) that break cut. Fields are numbered $1, $2, ..., and $NF is always the last one. For files with another separator, set it with -F.

1. Print columns

bash
awk '{print $1, $3}' /srv/data/inventory.txt | head -3
awk '{print $NF}' /srv/data/df.txt
PartMeaning
{print $1, $3}for every line, print fields 1 and 3. The comma puts a space between them.
$NFNF is the number of fields on the line, so $NF is the last field
text
HOST STATUS
web-01 running
web-02 running
on
/
/var/lib/docker
/data
/dev/shm
/backups

Even though the columns are separated by several spaces, awk found them correctly. (on comes from the header "Mounted on", which has two words.)

2. Another separator: -F

bash
awk -F: '{print $1, $6}' /etc/passwd | tail -3
PartMeaning
-F:fields are separated by :
$1, $6user name and home folder
text
asha /home/asha
vikram /home/vikram
meera /home/meera

3. Only the real users

System accounts (for services) have user IDs below 1000. Human accounts start at 1000. A pattern in front of the action filters lines:

bash
awk -F: '$3 >= 1000 && $3 < 60000 {print $1, $6}' /etc/passwd

What it does: prints name and home only where field 3 (the UID) is at least 1000 and below 60000 (the nobody account has 65534).

text
asha /home/asha
vikram /home/vikram
meera /home/meera
2 · Your task

Save the name and home folder (separated by a space) of every account with a UID from 1000 to 59999 to /root/users-home.txt.

Expected result: one line per human user, like asha /home/asha.

Hint: the commands, explained
text
awk -F: '$3 >= 1000 && $3 < 60000 {print $1, $6}' /etc/passwd > /root/users-home.txt

What each part does

  • -F: the fields in /etc/passwd are separated by colons.
  • $3 >= 1000 && $3 < 60000: only lines where field 3 (the UID) is in the range used for real people, not system accounts.
  • {print $1, $6}: print field 1 (user name) and field 6 (home folder), separated by a space.
  • > /root/users-home.txt saves the result. Each line looks like rohan /home/rohan.
First start the lab machine in the terminal panel on the right.

Patterns: choosing lines

Comparisons

OperatorMeaningExample
== / !=equal / not equal$3 == "running"
< <= > >=less / greater$5 >= 16
&& / || / !and / or / not$2 == "prod" && $3 == "running"

Text values go in double quotes. Numbers don't. awk decides whether a field is a number by looking at it, so $5 >= 16 compares numerically when field 5 holds digits.

bash
awk '$2 == "prod" && $3 == "running" {print $1}' inventory.txt
text
web-01
web-02
api-01
db-01
cache-01

Writing = instead of ==. awk '$3 = "running"' doesn't compare: it assigns "running" to field 3 on every line, so every line matches and gets printed with its third field changed. Always == for comparisons.

Regex patterns

PatternMatches lines where
/ERROR/the whole line matches the regex
$1 ~ /^web/field 1 matches (starts with "web")
$1 !~ /^web/field 1 does not match
/start/,/end/a range: from a line matching start to one matching end

Line numbers

NR == 1 is the header; NR > 1 skips it; NR % 2 == 0 selects even lines; NR >= 10 && NR <= 20 a range.

Try it · Task 2 of 4

Conditions

List the production servers that are running.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

A pattern can be any condition. If it's true for a line, the action runs; if you leave the action out, awk prints the whole line. Comparisons work on text ($3 == "running") and numbers ($5 >= 16), and you combine them with && (and), || (or) and ! (not). ~ tests a regex match.

1. Text comparison

bash
awk '$3 == "running"' /srv/data/inventory.txt

What it does: prints every line whose 3rd field is exactly running. Text values go in double quotes.

text
web-01      prod     running   4     8
web-02      prod     running   4     8
api-01      prod     running   8     16
api-02      staging  running   2     4
db-01       prod     running   16    64
cache-01    prod     running   2     32

Six running servers, including a staging one.

2. Numbers and skipping the header

bash
awk 'NR > 1 && $5 >= 16 {print $1, $5 "GB"}' /srv/data/inventory.txt
PartMeaning
NR > 1skip line 1, the header (NR is the line number)
$5 >= 16at least 16 GB of memory
$5 "GB"putting values next to each other joins them into one string
text
api-01 16GB
db-01 64GB
db-02 16GB
cache-01 32GB

3. Regex matches

bash
awk '$1 ~ /^web/' /srv/data/inventory.txt

What ~ does: the field must match the regex /^web/ (starts with "web"). !~ means "doesn't match".

text
web-01      prod     running   4     8
web-02      prod     running   4     8
web-03      prod     stopped   4     8
2 · Your task

Save the host names of all servers that are in the prod environment and have status running to /root/running-prod.txt, one per line.

Expected result: a list of host names only, without staging or stopped servers.

Hint: the commands, explained
text
awk '$2 == "prod" && $3 == "running" {print $1}' /srv/data/inventory.txt > /root/running-prod.txt

What each part does

  • Fields are separated by spaces by default, so no -F is needed.
  • $2 == "prod" && $3 == "running": keep lines where column 2 is exactly prod and column 3 is exactly running.
  • {print $1}: print only the first column, the server name.
First start the lab machine in the terminal panel on the right.

Variables and calculations

Variables need no declaration: they start as empty (0 in arithmetic) and keep their value from line to line. That's what makes totals possible.

OperationExample
arithmetic+ - * / % and ^ (power)
add tosum += $4
countn++
string joinx = $1 "-" $2 (just put values side by side)

BEGIN and END

BlockRuns
BEGIN { }once, before reading any input: set separators, print headers
END { }once, after the last line: print totals, averages, summaries
bash
awk 'NR > 1 {n++; sum += $4} END {print "servers:", n, "avg CPUs:", sum / n}' inventory.txt
PartRuns forDoes
NR > 1 {n++; sum += $4}each data linecount it, add its CPUs
END {print ...}once at the endprint the count and the average
text
servers: 8 avg CPUs: 5.5
text
ps aux | awk 'NR > 1 {mem += $6} END {printf "%.1f MB\n", mem / 1024}'   # total memory used by all processes
du -sk * | awk '{s += $1} END {print s/1024 " MB"}'                       # total size

Arrays: grouping

awk arrays use text keys, like a dictionary. They're the tool for "per group" questions, the equivalent of SQL's GROUP BY:

bash
awk -F, 'NR > 1 {rev[$1] += $4} END {for (r in rev) print r, rev[r]}' sales.csv | sort -k2 -nr
PartDoes
rev[$1] += $4add this line's revenue to the entry for its region
for (r in rev)in END, loop over every key that was used
print r, rev[r]print the key and its total
| sort -k2 -nrawk doesn't keep keys in order, so sort the result
text
south 1830000
north 1545000
east 1425000
west 1420000

Counting works the same way, with ++:

text
$ awk 'NR > 1 {count[$3]++} END {for (s in count) print s, count[s]}' inventory.txt
running 6
stopped 2

awk '{c[$1]++} END {for (k in c) print c[k], k}' access.log | sort -rn | head is the awk version of sort | uniq -c | sort -rn.

Try it · Task 3 of 4

Totals and groups

Calculate the total revenue of each region, highest first.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

awk has variables that keep their value from line to line, so it can add things up as it reads. Two special patterns run outside the per-line loop:

BlockRuns
BEGIN { ... }once, before the first line (set up, print a header)
END { ... }once, after the last line (print totals)

And arrays with text keys (rev["north"]) let you keep a separate total per group.

1. A total

bash
awk 'NR > 1 {total += $5} END {print "Total memory:", total, "GB"}' /srv/data/inventory.txt
PartMeaning
NR > 1 {total += $5}for every data line, add field 5 to total. Variables start at 0.
END {print ...}after all lines, print the result
text
Total memory: 156 GB

2. Count and average

bash
awk 'NR > 1 {n++; sum += $4} END {print "servers:", n, "avg CPUs:", sum / n}' /srv/data/inventory.txt

n++ adds 1 to n for each line; ; separates statements.

text
servers: 8 avg CPUs: 5.5

3. Totals per group, with an array

bash
awk -F, 'NR > 1 {rev[$1] += $4} END {for (r in rev) print r, rev[r]}' /srv/data/sales.csv
PartMeaning
-F,CSV: split on commas
rev[$1] += $4add the revenue (field 4) to the array entry named after the region (field 1)
for (r in rev) print r, rev[r]at the end, loop over every region and print it with its total
text
north 1545000
west 1420000
south 1830000
east 1425000

One line per region. awk doesn't keep arrays in any particular order, so pipe the result through sort -k2 -nr to rank them.

2 · Your task

Save the total revenue per region, as region total lines, sorted highest total first, to /root/revenue-by-region.txt.

Expected result: 4 lines, starting with south 1830000.

Hint: the commands, explained
text
awk -F, 'NR > 1 {rev[$1] += $4} END {for (r in rev) print r, rev[r]}' /srv/data/sales.csv | sort -k2 -nr > /root/revenue-by-region.txt

What each part does

  • -F, comma-separated file. NR > 1 skips line 1, the CSV header.
  • rev[$1] += $4: an array keyed by region (column 1); add each row's amount (column 4) to its region's total.
  • END {for (r in rev) print r, rev[r]}: after the last line, print every region and its total.
  • | sort -k2 -nr: sort by the 2nd column, numerically, in reverse (biggest first).
First start the lab machine in the terminal panel on the right.

if, and functions

Actions can contain if/else, loops and built-in functions:

text
awk '{ if ($5 > 80) print $6, "HIGH"; else print $6, "ok" }' df.txt
FunctionReturns / does
length(s)length of a string (length($0) for the line)
toupper(s) / tolower(s)change case
substr(s, start, len)part of a string: substr($1, 1, 3)
split(s, arr, sep)split a string into an array
sub(regex, repl, target)replace the first match (gsub for all)
int(x)whole-number part

Fields that aren't quite numbers

df shows usage as 89%. Two ways to get the number:

text
awk '{use = $5 + 0; ...}'            # + 0 converts using the leading digits: 89
awk '{sub("%", "", $5); ...}'        # remove the % sign from field 5

printf: formatted output

print separates values with a space and adds a newline. For aligned reports, use printf with a format string:

PlaceholderPrints
%sa string
%da whole number
%.2fa number with 2 decimals
%-12sa string, left-aligned, padded to 12 characters
%6da number, right-aligned in 6 characters
%%a literal %
\nnewline (printf never adds one itself)
bash
awk 'NR > 1 {use = $5 + 0; if (use > 80) printf "ALERT %-16s %3d%% used, %s free\n", $6, use, $4}' df.txt
text
ALERT /var/lib/docker   89% used, 22G free
ALERT /backups          93% used, 39G free

The mount points are padded to 16 characters, so the percentages line up.

Try it · Task 4 of 4

Formatted reports

Produce an alert line for every disk that is more than 80% full.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

print is quick, but for reports you want aligned columns and exact number formats. That's printf (print formatted): a format string with placeholders, followed by the values.

PlaceholderPrints
%sa string
%da whole number
%.1fa number with 1 decimal
%-16sa string left-aligned in a 16-character column
%5da number right-aligned in 5 characters
%%a literal % sign
\na new line (printf doesn't add one by itself)

1. The disk data

bash
cat /srv/data/df.txt
text
Filesystem      Size  Used Avail Use% Mounted on
/dev/nvme0n1p1   50G   21G   29G  42% /
/dev/nvme1n1    200G  178G   22G  89% /var/lib/docker
/dev/nvme2n1    100G   35G   65G  35% /data
tmpfs           3.9G     0  3.9G   0% /dev/shm
/dev/nvme3n1    500G  461G   39G  93% /backups

Field 5 is the usage, but with a % attached (89%), so it isn't a plain number yet.

2. Turn "89%" into a number

bash
awk 'NR > 1 {use = $5 + 0; if (use > 80) print $6, use}' /srv/data/df.txt
PartMeaning
use = $5 + 0adding 0 makes awk read 89% as a number: it takes the leading digits, 89
if (use > 80) print ...awk also has if, like other languages
text
/var/lib/docker 89
/backups 93

3. A formatted alert

bash
awk 'NR > 1 {use = $5 + 0; if (use > 80) printf "ALERT %-16s %3d%% used, %s free\n", $6, use, $4}' /srv/data/df.txt
text
ALERT /var/lib/docker   89% used, 22G free
ALERT /backups          93% used, 39G free

%-16s pads the mount point to 16 characters so the numbers line up, %3d%% prints the number and a percent sign. This is exactly the kind of line a monitoring script would send to Slack or email.

2 · Your task

Create /root/disk-alert.txt with one line for every filesystem that is more than 80% full. Each line must contain the mount point and the usage percentage (for example ALERT /backups 93% used, 39G free).

Expected result: exactly two lines, for /var/lib/docker and /backups.

Hint: the commands, explained
text
awk 'NR > 1 {use = $5 + 0; if (use > 80) printf "ALERT %-16s %3d%% used, %s free\n", $6, use, $4}' /srv/data/df.txt > /root/disk-alert.txt

What each part does

  • NR > 1 skips the header line of the df output.
  • use = $5 + 0: column 5 is like 91%; adding 0 turns it into the number 91.
  • if (use > 80): only filesystems more than 80% full.
  • printf "ALERT %-16s %3d%% used, %s free\n", $6, use, $4: formatted output: %-16s the mount point padded to 16 characters, %3d the number, %% a literal %, %s the free space.
First start the lab machine in the terminal panel on the right.

awk one-liners for DevOps

One-linerAnswers
awk '{print $1}' access.log | sort | uniq -c | sort -rn | headtop client IPs
awk '$9 >= 500' access.logrequests with a 5xx status (field 9 in the common log format)
awk '{print $9}' access.log | sort | uniq -cresponses per status code
df -h | awk 'NR > 1 && $5+0 > 80'filesystems over 80%
ps aux | awk '$3 > 50 {print $2, $11}'processes using more than 50% CPU (PID and command)
awk -F: '$3 == 0 {print $1}' /etc/passwdaccounts with UID 0 (should only be root)
kubectl get pods | awk '$3 != "Running" && NR > 1'pods that aren't running
awk -F, 'NR > 1 {s += $4} END {print s}' sales.csvsum a CSV column

cut, awk or sed? cut for quick columns from cleanly delimited files. awk when columns are space-aligned, or when you need conditions, calculations or grouping. sed for substitutions and line edits. And when an awk program grows past a couple of lines, it's usually time for a real script in bash or Python.

"How do you print the 2nd column of a file?" awk '{print $2}' file (or cut -d' ' -f2 if the separator is a single, consistent character).

"How do you sum a column?" awk '{s += $3} END {print s}' file.

"How do you find which users have UID 0?" awk -F: '$3 == 0 {print $1}' /etc/passwd. Anything besides root is a security red flag.

"How would you count requests per IP in an access log?" awk '{c[$1]++} END {for (ip in c) print c[ip], ip}' access.log | sort -rn | head.

Summary

  • awk splits each line into fields ($1 ... $NF, $0 the line), by default on whitespace; -F sets another separator.
  • Programs are pattern { action } rules. Patterns: comparisons (==, >=), &&/||, regex (/re/, ~, !~), NR > 1.
  • Variables persist across lines; BEGIN runs before input, END after: perfect for totals and averages.
  • Arrays with text keys group values: sum[$1] += $4, then for (k in sum).
  • printf formats output: %s, %d, %.2f, %-12s, %%, \n.
  • $5 + 0 turns 89% into a number; length, toupper, substr, split, sub/gsub are built in.
Check your understanding

Quick quiz

Feedback