Skip to content

awk for log analysis: answer questions about an access log in one line

Use awk to find top talkers, status distributions, top 404s, and per-minute error spikes in an nginx access log — on the server, without shipping the log anywhere.

You are on a server at 2am. No dashboard, no log aggregator, a 200 MB access.log. Someone wants to know who is hammering the site, what share of requests are failing, and which endpoint started returning 500s at 14:20. You need not ship that file anywhere or install anything — awk is already on the box, and each question is one line. This guide covers only the awk that earns its keep on a log: fields, BEGIN/END, and associative arrays as a counting primitive. It is not an awk language tutorial.

What you’ll accomplish

  • Read an nginx or Apache access log as fields, and know which field holds the IP, path, status, and bytes.
  • Count anything grouped by anything — hits per IP, requests per status, bytes per client — with one counting idiom.
  • Build an incident timeline showing which minute the errors started and which endpoint caused them.
  • Compute average, max, and p95 latency when your log format records them — and know why the default does not.
  • Cross-check your numbers, and know when to stop using awk entirely.

Prerequisites

Any awk will do. Which one you have depends on the system, and it matters less than people think:

  • gawk (GNU awk) — the default on RHEL, Rocky, and Fedora. The most featureful.
  • mawk — usually /usr/bin/awk on Debian and Ubuntu. Fast, smaller feature set.
  • BSD awk (the “one true awk”) — macOS and the BSDs.

Check with awk --version (gawk, one true awk) or awk -W version (mawk).

Everything here is POSIX-portable and runs unmodified on all three. Two gawk-only features are worth naming so you can avoid them on a server you do not control: gensub() and asort() / asorti(). On mawk or BSD awk they fail with calling undefined function gensub. Where sorting is needed, the work goes to sort — portable, and usually faster anyway.

To follow along, use a standard nginx combined access log. Every example below runs against a real 340-line log whose first line is:

203.0.113.130 - - [16/Jul/2026:14:15:00 +0000] "GET /api/v1/orders HTTP/1.1" 200 4402 "https://shop.example.com/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"

How it works

An awk program is a list of pattern { action } rules. awk reads one record (line) at a time and tests every pattern against it, running the action wherever a pattern matches. A rule with no pattern runs on every line; a rule with no action prints the line. So awk '$9 == 500' prints every line whose ninth field is 500 — a complete program.

Each record is split into fields by FS, the field separator. By default FS is a run of whitespace, so any number of spaces or tabs acts as one separator. $1 is the first field, $0 the whole unsplit line, and NF the number of fields on this line — so $NF is the last field and $(NF-1) the one before it. NR is the number of records read so far.

Two rules are special. BEGIN { } runs once before the first line, for headers and variables. END { } runs once after the last line, where you print what you accumulated. Between them awk loops over every line, which is why you never write a loop.

The counting primitive is the associative array. awk arrays are keyed by strings, and a key springs into existence the first time you touch it, with a value that starts empty and behaves as zero in arithmetic. So count[$1]++ means “add one to the bucket named by this line’s first field,” and after the last line count holds one entry per distinct IP. END { for (k in count) print count[k], k } walks it. That one idiom is most of what follows.

Field map of an nginx combined log line split into $1 to $12 — client IP at $1, timestamp at $4, path at $7, status at $9, bytes at $10 — beside the BEGIN, per-line rule and END lifecycle feeding an associative array of counts

The field map is the thing to memorize. On a default nginx combined line: $1 is the client IP, $4 the timestamp, $7 the request path, $9 the status code, $10 the bytes sent.

Step-by-step

1. Confirm the field map on your own log. Never trust a field number you read online, this page included — log formats get customized. Print one line’s fields with their indexes:

head -1 access.log | awk '{for (i = 1; i <= NF; i++) printf "$%-3d= %s\n", i, $i; print "NF = " NF}'
$1  = 203.0.113.130
$2  = -
$3  = -
$4  = [16/Jul/2026:14:15:00
$5  = +0000]
$6  = "GET
$7  = /api/v1/orders
$8  = HTTP/1.1"
$9  = 200
$10 = 4402
$11 = "https://shop.example.com/"
$12 = "Mozilla/5.0
$13 = (X11;
$14 = Linux
$15 = x86_64)
$16 = AppleWebKit/537.36
$17 = (KHTML,
$18 = like
$19 = Gecko)
$20 = Chrome/126.0.0.0
$21 = Safari/537.36"
NF = 21

Two things to notice. The bracketed timestamp splits across $4 and $5, because of the space before the timezone. And the user agent shatters into ten fields, $12 to $21 — which is why anything appended after it must be counted from the right with NF, never from the left.

2. Find the top talkers. The counting idiom, then sort -rn | head to rank it. awk does not sort, and does not need to:

awk '{count[$1]++} END {for (ip in count) print count[ip], ip}' access.log | sort -rn | head -5
90 198.51.100.23
78 203.0.113.42
41 203.0.113.87
26 192.0.2.14
4 203.0.113.166

One client made 90 of 340 requests — your answer to “who is hammering us.”

3. Add a header and column alignment with BEGIN and printf. Note the END trick: piping only the data rows to sort keeps the header on top, since the header goes straight to stdout while rows go through the pipe:

awk 'BEGIN {printf "%6s  %s\n", "HITS", "CLIENT"}
     {count[$1]++}
     END {for (ip in count) printf "%6d  %s\n", count[ip], ip | "sort -rn"}' access.log | head -6
  HITS  CLIENT
    90  198.51.100.23
    78  203.0.113.42
    41  203.0.113.87
    26  192.0.2.14
     4  203.0.113.166

4. Get the status code distribution. Count two things at once — the per-status bucket and a running total — then do the arithmetic in END. %% prints a literal percent:

awk '{count[$9]++; total++} END {for (s in count) printf "%-6s %6d  %5.1f%%\n", s, count[s], 100*count[s]/total}' access.log | sort -k2 -rn
200       264   77.6%
500        42   12.4%
404        34   10.0%

12.4% of requests are failing. That is not a healthy server.

5. Find the top 404 paths. Here the pattern does the filtering and the action does the counting — only lines with status 404 ever reach count[$7]++:

awk '$9 == 404 {count[$7]++} END {for (p in count) print count[p], p}' access.log | sort -rn | head -5
11 /old-pricing
7 /wp-login.php
6 /favicon.ico
6 /admin/config.php
4 /.env

Two stories in one table. /old-pricing is a real broken link worth fixing; /wp-login.php, /admin/config.php, and /.env are a scanner poking at a site that does not run WordPress. Only the first is yours to fix.

6. Build a per-minute timeline. The timestamp lives in $4 as [16/Jul/2026:14:15:00. split() cuts a string into an array on a separator, so splitting on : puts the hour in t[2] and the minute in t[3]:

awk '{split($4, t, ":"); count[t[2] ":" t[3]]++} END {for (m in count) print m, count[m]}' access.log | sort
14:15 17
14:16 20
14:17 24
14:18 19
14:19 21
14:20 43
14:21 44
14:22 36
14:23 43
14:24 33
14:25 40

Traffic roughly doubles at 14:20 — which alone could mean a real spike or clients retrying failures.

7. Pivot status by minute to find the incident. This is the one that answers “which endpoint started 500ing at 14:20.” A two-dimensional key (c[m, $9]) counts each status within each minute:

awk '{split($4, t, ":"); m = t[2] ":" t[3]; seen[m] = 1; c[m, $9]++}
     END {printf "%-8s %6s %6s %6s\n", "MINUTE", "200", "404", "500"
          for (m in seen) printf "%-8s %6d %6d %6d\n", m, c[m,"200"], c[m,"404"], c[m,"500"] | "sort"}' access.log
MINUTE      200    404    500
14:15        15      2      0
14:16        14      6      0
14:17        21      3      0
14:18        17      2      0
14:19        17      4      0
14:20        36      1      6
14:21        33      2      9
14:22        23      3     10
14:23        33      5      5
14:24        26      4      3
14:25        29      2      9

Zero 500s before 14:20, then they start and never stop. Now ask which endpoint:

awk '$9 == 500 {count[$7]++} END {for (p in count) print count[p], p}' access.log | sort -rn
42 /api/v1/orders

Every 500 came from one endpoint. Three commands took you from “the site is broken” to “/api/v1/orders began failing at 14:20.”

8. Sum bytes by client. Counting used ++; summing uses +=. $10 is bytes sent:

awk '{bytes[$1] += $10} END {for (ip in bytes) printf "%10.2f MB  %s\n", bytes[ip]/1048576, ip}' access.log | sort -rn | head -5
      1.39 MB  198.51.100.23
      1.24 MB  203.0.113.42
      0.63 MB  203.0.113.87
      0.25 MB  192.0.2.14
      0.13 MB  203.0.113.137

9. Measure latency — but check your log format first. The honest part: $upstream_response_time is not in nginx’s default combined format. Neither is $request_time. If you have not customized log_format, no amount of awk will recover timings that were never written. You need this in nginx, and a reload, before any of it exists:

log_format timed '$remote_addr - $remote_user [$time_local] "$request" '
                 '$status $body_bytes_sent "$http_referer" "$http_user_agent" '
                 'rt=$request_time uct="$upstream_connect_time" urt="$upstream_response_time"';

access_log /var/log/nginx/access.log timed;

Once that format is live, every new line ends with rt=0.130 uct="0.001" urt="0.128" — three fields the examples above did not have. The next two commands only work on lines written this way; on a plain combined log $NF is the tail of the user agent, not a number.

Since the user agent holds an unpredictable number of spaces, do not count from the left — count from the right with NF. The last three fields are always $(NF-2), $(NF-1), $NF. Strip the label and quotes with gsub(), then force a number by adding zero:

awk '{urt = $NF; gsub(/[^0-9.]/, "", urt); urt = urt + 0;
      sum[$7] += urt; n[$7]++; if (urt > max[$7]) max[$7] = urt}
     END {for (p in n) printf "%7.3f %7.3f %6d  %s\n", sum[p]/n[p], max[p], n[p], p}' access.log | sort -rn | head -8
  3.781   9.501     70  /api/v1/orders
  0.219   0.336     27  /products/widget-mini
  0.211   0.335     33  /api/v1/session
  0.211   0.333     22  /
  0.187   0.338     24  /cart
  0.176   0.337     22  /checkout
  0.158   0.334     30  /products/widget-pro
  0.018   0.027      6  /favicon.ico

Columns are average, max, count, path. /api/v1/orders averages 3.8 seconds against roughly 0.2 for everything else — the same endpoint the 500s came from; the timing says it is waiting on something.

10. Compute a p95 without gawk. A percentile needs sorted data, and portable awk cannot sort an array. So split the job: awk extracts the numbers, sort -n orders them, and a second awk indexes into the sorted stream:

awk '{urt = $NF; gsub(/[^0-9.]/, "", urt); print urt + 0}' access.log | sort -n | awk '{a[NR] = $1} END {print "p50 =", a[int(NR*0.50)]; print "p95 =", a[int(NR*0.95)]; print "p99 =", a[int(NR*0.99)]; print "n   =", NR}'
p50 = 0.128
p95 = 7.015
p99 = 9.031
n   = 340

A healthy 128ms median beside a 7-second p95 is the exact shape of “most requests are fine, one slice is on fire.” Averages hide that; percentiles do not.

Validate it works

Never hand someone a number you have not cross-checked. Two cheap checks catch most mistakes.

Check a count against grep -c. If two tools disagree, one of them is wrong:

awk '$9 == 404' access.log | wc -l
grep -c '" 404 ' access.log
      34
34

They agree — but note why awk is the more trustworthy of the two: it tests the status field specifically, while a naive grep -c 404 also matches a byte count of 404, an IP containing 404, or a URL with 404 in it. Use grep as a sanity check, not as the source of truth.

Check that your buckets sum to the line count. Grouped totals must add up to every line in the file, or your pattern is silently dropping records:

awk '{count[$9]++} END {for (s in count) total += count[s]; print "sum of buckets:", total}' access.log
wc -l < access.log
sum of buckets: 340
     340

Every line landed in exactly one bucket. Had the sum come up short, some lines would have a field 9 you did not expect — a second log format mixed into the same file, or a malformed line.

Troubleshooting

  • Your shell ate $1 — always single-quote the program. Inside double quotes the shell expands $1 (usually to nothing) before awk sees it, so awk "{print $1}" becomes awk "{print }" — and a bare print prints the whole line. The symptom is unmistakable: you asked for one column and got whole log lines. Single-quote the program, every time. To pass a shell value in, use awk -v ip="$SOME_IP" '$1 == ip'.
  • The default FS collapses whitespace; -F, does not. With the default separator a run of spaces counts as one, so a c has two fields. With an explicit single-character separator every separator counts: a,,c has three fields and $2 is empty. That difference is deliberate, and it is why an empty value shifts columns on a space-separated log but not in a CSV. Confirm with awk -F, '{print NF}' before trusting a column.
  • The nginx timestamp spans two fields. [16/Jul/2026:14:15:00 +0000] has a space before the timezone, so $4 is [16/Jul/2026:14:15:00 and $5 is +0000]. Expecting one field gets you a truncated stamp with a stray [. Strip it with sub(/^\[/, "", ts) and split the rest on :; the timezone is in $5.
  • Numbers compared as strings give wrong answers. awk picks numeric or string comparison based on how a value was produced. A field straight from the input compares numerically, but once you run it through sub(), gsub(), or concatenation it is a string — and "9.500" > "12.300" is true as strings, because 9 sorts after 1. This bites the max-tracking recipe in step 9: without urt = urt + 0 it reports 9.500 as the maximum of a set containing 12.300. Add zero after any string surgery. The classic form is "010" versus "9": numerically 10 wins, as strings "9" does.
  • awk looks frozen on tail -f. When awk’s output goes to a pipe or file rather than a terminal it is block-buffered, so nothing appears until a few kilobytes accumulate. On a live log that can take minutes and looks like a hang. Call fflush() after printing to push each line out immediately:
tail -f access.log | awk '$9 == 500 {print $1, $7; fflush()}'

fflush() works in gawk, mawk, and BSD awk. Note too that END never runs on a tail -f pipe because the input never ends, so counting idioms that print in END print nothing. For live work, print per line instead of accumulating.

When this is the wrong approach

awk is an incident tool, not a monitoring strategy. If these questions come up more than occasionally, stop answering them by hand: ship logs to Loki, OpenSearch, or a hosted service and get the retention and alerting a one-liner never will. The point of a pipeline is that nobody has to SSH anywhere at 2am.

For interactive exploration, goaccess gives you a live terminal dashboard with sessions, referrers, and geolocation for far less effort than assembling it from awk. Reach for it when you want to browse rather than answer one precise question — see analyzing Apache logs with goaccess.

Watch for sampling bias. access.log is only the current rotation — the incident may already sit in access.log.1 or a .gz, and your “top talker” leads only since the last rotation. Check ls -la /var/log/nginx/ first, and read archives with zcat access.log.*.gz | awk ....

Finally, respect the size. awk streams and uses little memory, so it handles big files better than most tools — but a pass over 40 GB is still bounded by disk reads, and arrays grow with the number of distinct keys, so grouping 40 GB by URL with query strings can exhaust memory. Narrow with grep or a time slice first, then let awk work on what is left.

The GNU Awk User’s Guide is the best awk documentation there is, and the POSIX awk specification is the arbiter of what is portable. The same “aggregate, don’t eyeball” instinct applies to databases — see reading the MySQL slow query log. And when awk says an endpoint is slow but not why, break the request down by phase with curl.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.