How-to

The awk Command for Server Admins

awk reads text line by line, splits each line into fields and runs a small program on them. It turns log files and command output into answers in one line.

What does awk actually do?

awk treats every input line as a record and every whitespace-separated word on it as a field. Field one is $1, field two is $2, the whole line is $0 and the number of fields is NF. A program is a list of pattern { action } pairs: when the pattern matches a line, the action runs. Leave out the pattern and the action runs on every line; leave out the action and awk prints the matching line. That small model covers most of what admins need from it on a server: picking columns, filtering rows and adding numbers up.

Every image we install ships an awk. Ubuntu and Debian default to mawk, which is very fast; Rocky Linux, AlmaLinux and CentOS Stream ship GNU gawk, which has more built-in functions. FreeBSD has its own one-true-awk. Everything on this page runs on all of them unless it says gawk.

How do I print one column?

df -hP | awk '{ print $1, $5 }'
ps -eo user=,rss=,comm= | awk '$2 > 200000 { print $1, $3 }'

The first line shows each file system with its use percentage. The second lists processes using more than about 200 MB of resident memory, with their owner and name. Notice that the comparison $2 > 200000 is numeric: awk converts fields to numbers when they look like numbers, so you do not need to cast anything.

The last column is $NF and the one before it is $(NF-1). That is handy when lines have a varying number of words, for example a path at the end of a line whose middle part changes.

How do I change the field separator?

Use -F for input and the OFS variable for output:

awk -F: '$3 >= 1000 && $7 !~ /nologin/ { print $1 }' /etc/passwd
awk -F, -v OFS='\t' '{ $1 = $1; print }' export.csv

The first command lists real login accounts on the box: user id 1000 or higher and a shell that is not nologin. The second turns a simple CSV into tab-separated text; assigning $1 = $1 forces awk to rebuild the line with the new separator. awk does not understand quoted CSV fields that contain commas, so use a real CSV tool for exports from spreadsheets.

How do I add up numbers from a log?

This is where awk saves the most time. In the default combined log format of nginx, field 10 is the response size in bytes:

awk '{ sent += $10 } END { printf "%.2f GB\n", sent / 1e9 }' /var/log/nginx/access.log

The END block runs once after the last line. Run the same line over yesterday's rotated log and you have a quick estimate of how much traffic your web server pushed out. On our machines outgoing traffic has a monthly allowance (15 TB in five cities, 5 TB in Singapore), so a daily check like this tells you early whether a busy site is drifting toward it. Outbound traffic allowance explains the allowance in detail.

How do I count by key?

awk arrays are associative, so counting is a one-liner:

awk '{ hits[$1]++ } END { for (ip in hits) print hits[ip], ip }' access.log | sort -rn | head -15
awk '$9 ~ /^5/ { e[$7]++ } END { for (u in e) print e[u], u }' access.log | sort -rn | head

The first shows the fifteen busiest client addresses, useful when one scraper is eating your bandwidth. The second lists the URLs that returned 5xx errors, most frequent first. Piping into sort -rn is simpler than sorting inside awk, and it works the same on mawk and gawk.

Which built-in variables matter?

VariableMeaningTypical use
NRLine number across all inputNR > 1 skips a header line
FNRLine number in the current fileReading two files at once
NFFields on this lineNF == 0 finds blank lines
FS / OFSInput and output separatorsSet in BEGIN or with -F
FILENAMECurrent input fileTagging output from many logs

How do I pass a shell variable into awk?

Use -v, never string splicing. Splicing breaks on spaces and quotes and can run unexpected code.

limit=85
df -P | awk -v max="$limit" 'NR > 1 { sub(/%/, "", $5); if ($5 + 0 > max) print $6, $5 "%" }'

That prints every mount point above 85 percent full, which makes a neat cron check. Pair it with Set up a cron job and mail or a webhook, and you hear about a filling disk before a database stops writing.

When should I write an awk script file?

Once a one-liner passes three lines, move it into a file and run it with awk -f. Comments and indentation make it readable months later:

# /usr/local/lib/slowreq.awk : requests slower than 2 s, by path
$NF > 2.0 { slow[$7]++; t[$7] += $NF }
END { for (p in slow) printf "%6d %8.2f %s\n", slow[p], t[p] / slow[p], p }

This expects a log format with request time as the last field (add $request_time at the end of your nginx log_format). Run it with awk -f /usr/local/lib/slowreq.awk /var/log/nginx/timed.log | sort -rn.

awk, sed or grep?

Use grep to find lines, sed to edit text in a stream, and awk when you need fields, arithmetic or grouping. They chain well: grep narrows a huge log fast, awk does the math on what is left. For sed patterns see The sed command; for fast line matching see The grep command.

On large logs, mawk on an S1 or S4 chews through gigabytes in seconds, because a single awk process uses one core at a high clock. If you need to process many files at once, run several awk processes in parallel with xargs -P and let a many-core box like D3 spread the work.

Machines That Crunch Logs Quickly

ServerProcessorCores / threadsMemoryStorageNetworkPer monthSmallest order
S1Intel Xeon E-2276G6 / 1264 GB DDR41x 1 TB NVMe2x 10 Gbps$53.32$53.32 (1 month)
S4Intel Xeon E-2388G8 / 1664 GB DDR41x 1 TB NVMe2x 10 Gbps$87.52$87.52 (1 month)
S11Intel Core i9-14900K24 / 32128 GB DDR52x 2 TB NVMe2x 10 Gbps$149.39$149.39 (1 month)
D32x Intel Xeon Gold 6258R56 / 112128 GB DDR42x 1 TB NVMe2x 25 Gbps$275.32$275.32 (1 month)

Keep Reading

The sed command

Edit text streams and files with sed: substitutions, in-place edits with backups, line addresses, extended regex, multiple commands and GNU versus BSD.

Open

Count matches with grep

Count matching lines, every match, matches per file and per value with grep -c, -o and a few pipes, plus common counting traps.

Open

Check CPU usage and load

Read load averages against your thread count, split CPU time by type with mpstat and vmstat, find the busy process and keep history with sar.

Open

Outbound traffic allowance

How the 15 TB monthly egress allowance works, what it means per day and per second, and why inbound data costs nothing.

Open

FAQ

Quick Answers

Yes. Ubuntu and Debian include mawk, Rocky Linux, AlmaLinux and CentOS Stream include gawk, and FreeBSD has its own awk in the base system.

Use awk '{ print $NF }'. NF is the number of fields, so $NF is always the last one.

Add the pattern NR > 1 in front of the action, so the first line is ignored.

Plain awk splits on every comma, including those inside quotes. gawk has an FPAT variable that helps, but a dedicated CSV tool is safer for complex exports.

Single quotes stop the shell from expanding it. Pass it in with -v name="$value" and use name inside the program.