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.
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
web-01 prod running 4 8$0 is the whole line. NF = 5 (number of fields). NR = the line number.
For each line, awk:
- reads it into
$0, - splits it into fields
$1,$2, ... (by default on runs of spaces or tabs, ignoring spaces at the start), - runs your program on it,
- 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:
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.
| Program | Does |
|---|---|
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
awk '{print $1, $3}' inventory.txt | head -3
awk '{print $NF}' df.txtHOST STATUS
web-01 running
web-02 runningon
/
/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.
| Expression | Value |
|---|---|
$1, $2, ... | field 1, 2, ... |
$0 | the whole line |
$NF | the last field |
$(NF-1) | the second-to-last field |
NF | how many fields this line has |
NR | the line number (across all files) |
FNR | the line number within the current file |
FILENAME | the name of the current file |
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 -lChoosing the separator: -F, FS and OFS
For files with a fixed delimiter, set the input field separator:
| Command | Splits on |
|---|---|
awk -F, '...' | commas (CSV) |
awk -F: '...' | colons (/etc/passwd) |
awk -F'\t' '...' | tabs |
awk -F'[,;]' '...' | a regex: comma or semicolon |
awk -F: '{print $1, $6}' /etc/passwd | tail -3asha /home/asha
vikram /home/vikram
meera /home/meeraInside the program, the same settings are the variables FS (input separator) and OFS (output separator), usually set in a BEGIN block:
$ awk 'BEGIN {FS=","; OFS=" | "} NR > 1 {print $1, $2, $4}' sales.csv | head -3
north | laptop | 840000
south | phone | 1200000
west | laptop | 490000Fields and separators
List the real user accounts with their home folders.
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
awk '{print $1, $3}' /srv/data/inventory.txt | head -3
awk '{print $NF}' /srv/data/df.txt| Part | Meaning |
|---|---|
{print $1, $3} | for every line, print fields 1 and 3. The comma puts a space between them. |
$NF | NF is the number of fields on the line, so $NF is the last field |
HOST STATUS
web-01 running
web-02 running
on
/
/var/lib/docker
/data
/dev/shm
/backupsEven 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
awk -F: '{print $1, $6}' /etc/passwd | tail -3| Part | Meaning |
|---|---|
-F: | fields are separated by : |
$1, $6 | user name and home folder |
asha /home/asha
vikram /home/vikram
meera /home/meera3. 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:
awk -F: '$3 >= 1000 && $3 < 60000 {print $1, $6}' /etc/passwdWhat it does: prints name and home only where field 3 (the UID) is at least 1000 and below 60000 (the nobody account has 65534).
asha /home/asha
vikram /home/vikram
meera /home/meeraSave 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
awk -F: '$3 >= 1000 && $3 < 60000 {print $1, $6}' /etc/passwd > /root/users-home.txtWhat each part does
-F:the fields in/etc/passwdare 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.txtsaves the result. Each line looks likerohan /home/rohan.
Patterns: choosing lines
Comparisons
| Operator | Meaning | Example |
|---|---|---|
== / != | 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.
awk '$2 == "prod" && $3 == "running" {print $1}' inventory.txtweb-01
web-02
api-01
db-01
cache-01Writing = 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
| Pattern | Matches 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.
Conditions
List the production servers that are running.
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
awk '$3 == "running"' /srv/data/inventory.txtWhat it does: prints every line whose 3rd field is exactly running. Text values go in double quotes.
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 32Six running servers, including a staging one.
2. Numbers and skipping the header
awk 'NR > 1 && $5 >= 16 {print $1, $5 "GB"}' /srv/data/inventory.txt| Part | Meaning |
|---|---|
NR > 1 | skip line 1, the header (NR is the line number) |
$5 >= 16 | at least 16 GB of memory |
$5 "GB" | putting values next to each other joins them into one string |
api-01 16GB
db-01 64GB
db-02 16GB
cache-01 32GB3. Regex matches
awk '$1 ~ /^web/' /srv/data/inventory.txtWhat ~ does: the field must match the regex /^web/ (starts with "web"). !~ means "doesn't match".
web-01 prod running 4 8
web-02 prod running 4 8
web-03 prod stopped 4 8Save 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
awk '$2 == "prod" && $3 == "running" {print $1}' /srv/data/inventory.txt > /root/running-prod.txtWhat each part does
- Fields are separated by spaces by default, so no
-Fis needed. $2 == "prod" && $3 == "running": keep lines where column 2 is exactlyprodand column 3 is exactlyrunning.{print $1}: print only the first column, the server name.
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.
| Operation | Example |
|---|---|
| arithmetic | + - * / % and ^ (power) |
| add to | sum += $4 |
| count | n++ |
| string join | x = $1 "-" $2 (just put values side by side) |
BEGIN and END
| Block | Runs |
|---|---|
BEGIN { } | once, before reading any input: set separators, print headers |
END { } | once, after the last line: print totals, averages, summaries |
awk 'NR > 1 {n++; sum += $4} END {print "servers:", n, "avg CPUs:", sum / n}' inventory.txt| Part | Runs for | Does |
|---|---|---|
NR > 1 {n++; sum += $4} | each data line | count it, add its CPUs |
END {print ...} | once at the end | print the count and the average |
servers: 8 avg CPUs: 5.5ps 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 sizeArrays: grouping
awk arrays use text keys, like a dictionary. They're the tool for "per group" questions, the equivalent of SQL's GROUP BY:
awk -F, 'NR > 1 {rev[$1] += $4} END {for (r in rev) print r, rev[r]}' sales.csv | sort -k2 -nr| Part | Does |
|---|---|
rev[$1] += $4 | add 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 -nr | awk doesn't keep keys in order, so sort the result |
south 1830000
north 1545000
east 1425000
west 1420000Counting works the same way, with ++:
$ awk 'NR > 1 {count[$3]++} END {for (s in count) print s, count[s]}' inventory.txt
running 6
stopped 2awk '{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.
Totals and groups
Calculate the total revenue of each region, highest first.
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:
| Block | Runs |
|---|---|
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
awk 'NR > 1 {total += $5} END {print "Total memory:", total, "GB"}' /srv/data/inventory.txt| Part | Meaning |
|---|---|
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 |
Total memory: 156 GB2. Count and average
awk 'NR > 1 {n++; sum += $4} END {print "servers:", n, "avg CPUs:", sum / n}' /srv/data/inventory.txtn++ adds 1 to n for each line; ; separates statements.
servers: 8 avg CPUs: 5.53. Totals per group, with an array
awk -F, 'NR > 1 {rev[$1] += $4} END {for (r in rev) print r, rev[r]}' /srv/data/sales.csv| Part | Meaning |
|---|---|
-F, | CSV: split on commas |
rev[$1] += $4 | add 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 |
north 1545000
west 1420000
south 1830000
east 1425000One line per region. awk doesn't keep arrays in any particular order, so pipe the result through sort -k2 -nr to rank them.
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
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.txtWhat each part does
-F,comma-separated file.NR > 1skips 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).
if, and functions
Actions can contain if/else, loops and built-in functions:
awk '{ if ($5 > 80) print $6, "HIGH"; else print $6, "ok" }' df.txt| Function | Returns / 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:
awk '{use = $5 + 0; ...}' # + 0 converts using the leading digits: 89
awk '{sub("%", "", $5); ...}' # remove the % sign from field 5printf: formatted output
print separates values with a space and adds a newline. For aligned reports, use printf with a format string:
| Placeholder | Prints |
|---|---|
%s | a string |
%d | a whole number |
%.2f | a number with 2 decimals |
%-12s | a string, left-aligned, padded to 12 characters |
%6d | a number, right-aligned in 6 characters |
%% | a literal % |
\n | newline (printf never adds one itself) |
awk 'NR > 1 {use = $5 + 0; if (use > 80) printf "ALERT %-16s %3d%% used, %s free\n", $6, use, $4}' df.txtALERT /var/lib/docker 89% used, 22G free
ALERT /backups 93% used, 39G freeThe mount points are padded to 16 characters, so the percentages line up.
Formatted reports
Produce an alert line for every disk that is more than 80% full.
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.
| Placeholder | Prints |
|---|---|
%s | a string |
%d | a whole number |
%.1f | a number with 1 decimal |
%-16s | a string left-aligned in a 16-character column |
%5d | a number right-aligned in 5 characters |
%% | a literal % sign |
\n | a new line (printf doesn't add one by itself) |
1. The disk data
cat /srv/data/df.txtFilesystem 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% /backupsField 5 is the usage, but with a % attached (89%), so it isn't a plain number yet.
2. Turn "89%" into a number
awk 'NR > 1 {use = $5 + 0; if (use > 80) print $6, use}' /srv/data/df.txt| Part | Meaning |
|---|---|
use = $5 + 0 | adding 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 |
/var/lib/docker 89
/backups 933. A formatted alert
awk 'NR > 1 {use = $5 + 0; if (use > 80) printf "ALERT %-16s %3d%% used, %s free\n", $6, use, $4}' /srv/data/df.txtALERT /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.
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
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.txtWhat each part does
NR > 1skips the header line of thedfoutput.use = $5 + 0: column 5 is like91%; 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:%-16sthe mount point padded to 16 characters,%3dthe number,%%a literal %,%sthe free space.
awk one-liners for DevOps
| One-liner | Answers |
|---|---|
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head | top client IPs |
awk '$9 >= 500' access.log | requests with a 5xx status (field 9 in the common log format) |
awk '{print $9}' access.log | sort | uniq -c | responses 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/passwd | accounts 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.csv | sum 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,$0the line), by default on whitespace;-Fsets another separator. - Programs are
pattern { action }rules. Patterns: comparisons (==,>=),&&/||, regex (/re/,~,!~),NR > 1. - Variables persist across lines;
BEGINruns before input,ENDafter: perfect for totals and averages. - Arrays with text keys group values:
sum[$1] += $4, thenfor (k in sum). printfformats output:%s,%d,%.2f,%-12s,%%,\n.$5 + 0turns89%into a number;length,toupper,substr,split,sub/gsubare built in.
Quick quiz
You've practised everything in this lesson
Every task was checked on your own machine. You can end the lab, or keep experimenting in the terminal.