Skip to content
KALANBLON
Show contents

Chapter 2 of 7 · 20 min

Analysing logs with awk and sed

By the end of this chapter, you'll be able to

  • Split a line into fields and filter lines with awk
  • Compute sums, averages and totals per key with awk
  • Transform text with sed and its substitutions
  • Chain awk, sort and uniq to produce a ranking

The log to analyse

A log is a file where a program records what it does, one line per event. Here is a simplified extract of a web server log: the client's address, the method, the page, the HTTP response code and the response time in milliseconds.

cat > access.log <<'EOF'
10.0.0.5 GET /home 200 120
10.0.0.8 GET /products 200 340
10.0.0.5 POST /cart 500 2100
10.0.0.9 GET /home 200 95
10.0.0.8 GET /products 404 15
10.0.0.5 GET /payment 500 1800
10.0.0.7 GET /home 200 110
EOF
wc -l access.log
7 access.log

awk: a language for columns

awk reads a file line by line and splits each line into fields, separated by spaces: $1 is the first field, $2 the second, $0 the whole line, NF the number of fields and NR the line number. An awk program is a series of rules of the form pattern { action }: the action runs for every line that matches the pattern.

awk '$4 == 500 { print $3, $5 " ms" }' access.log
/cart 2100 ms
/payment 1800 ms

The pattern $4 == 500 keeps the lines whose response code is 500 (server error); the action prints the page and the time.

The special BEGIN and END blocks run before the first line and after the last one. They are used to prepare and conclude a calculation:

awk '{ total += $5 } END { print NR, "requests, average time:", total / NR, "ms" }' access.log
7 requests, average time: 654.286 ms

Totals per key

awk has associative arrays: nb[$1]++ counts the lines of each address, like a dictionary. Their iteration order is not guaranteed: sort the result with sort.

awk '{ nb[$1]++; time[$1] += $5 }
     END { for (ip in nb) print nb[ip], ip, time[ip] / nb[ip] " ms" }' access.log | sort -k1,1nr -k2,2
3 10.0.0.5 1340 ms
2 10.0.0.8 177.5 ms
1 10.0.0.7 110 ms
1 10.0.0.9 95 ms

sort -k1,1nr sorts on the first field, numerically (n), in descending order (r); -k2,2 breaks ties by address.

After the last line, the END block goes through the array and prints each total.

Step 5 of 5
Text description of the animation
  1. awk will read the lines one by one. The nb array starts empty.
  2. Line 1: the address 10.0.0.5 gets its slot, which goes to 1.
  3. Line 2: a new address, a new slot.
  4. Line 3: 10.0.0.5 comes back, its slot goes to 2.
  5. After the last line, the END block goes through the array and prints each total.

sed: search and replace

sed (stream editor) transforms text on the fly. Its most used command is the substitution s/pattern/replacement/; with g at the end, it replaces every occurrence in the line. For example, to anonymise the addresses before sharing the log:

sed -E 's/^([0-9]+\.[0-9]+\.[0-9]+)\.[0-9]+/\1.x/' access.log | head -3
10.0.0.x GET /home 200 120
10.0.0.x GET /products 200 340
10.0.0.x POST /cart 500 2100

-E enables extended regular expressions: [0-9]+ means "one or more digits", \. a literal dot, and the brackets capture a group that \1 copies into the replacement.

Mini-lab: ranking the requested pagesTerminal simulator

Terminal

Click “Run”: the commands run in a fresh terminal, in your home folder /home/awa. Type “help” for the list of commands.

Teaching simulator: it reproduces the essential Linux commands in your browser, with nothing to install · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: the error report

From access.log, print for each response code the number of requests and the maximum response time, sorted by code. Finish with the percentage of requests in error (code 400 or more), rounded down to a whole number.

Hint 1
In awk, keep nb[$4]++ and, for the maximum, if ($5 > max[$4]) max[$4] = $5.
Hint 2
For the percentage, count the lines where $4 >= 400 in a variable, then use printf "%d%%\n", errors * 100 / NR in the END block. Use two separate commands: one for the sorted table, one for the percentage.
Show the solution and common mistakes
awk '{ nb[$4]++; if ($5 > max[$4]) max[$4] = $5 }
     END { for (c in nb) print c, nb[c], "requests, max", max[c], "ms" }' access.log | sort -n
awk '$4 >= 400 { errors++ } END { printf "%d%% of requests in error\n", errors * 100 / NR }' access.log
200 4 requests, max 340 ms
404 1 requests, max 15 ms
500 2 requests, max 2100 ms
42% of requests in error

3 requests out of 7 are errors: 42.86%, which %d truncates to 42.

Common mistakes:

  • Printing the percentage in the same command as the table, before sort: the percentage line would be sorted with the others.
  • Writing $4 > 400: code 400 itself (bad request) would be missed.
  • Comparing fields that are not numbers: awk then compares texts, and "90" is greater than "2100".

Summary

  1. 1awk splits each line into fields ($1, $2…) and applies “pattern { action }” rules.
  2. 2BEGIN and END frame the reading: ideal for setting up and concluding a calculation.
  3. 3awk's associative arrays compute totals per key; sort the result afterwards with sort.
  4. 4sed s/pattern/replacement/ transforms text, for example to anonymise a log.
  5. 5Set the separator with -F as soon as fields are not separated by spaces.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.