Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Lab · 30 min · revision 1

Lab: from a raw access log to a report with grep, sed and awk

Turn two compressed days and one plain day of access logs into a per-hour status table, a top-clients list joined with owners, a slowest-endpoints table and a CSV file, validating the format first and using awk associative arrays for the aggregation.

Contentsand lesson path

What you will learn

  • Write basic and extended regular expressions and use grep -E, sed and awk to filter, extract, transform and summarise log and CSV data.

Prerequisites: Scripting Basics

01. Goal and setup

An on-call colleague asks three questions about the shop API: how many requests ended with each status code in each hour, which client addresses sent the most traffic, and which endpoints were slowest. The answers are in the web server's access logs: two rotated, gzip-compressed days and today's plain file. You will answer all three with grep -E, sed and awk, and you will check the parse before you trust any number.

The lab demonstrates one principle: a report is only as good as its parse. Validate the format first, normalise what should count as "the same", and only then aggregate. The aggregation itself uses awk associative arrays, tables indexed by a string such as an IP address, which replace long sort | uniq -c chains when you need several numbers per key. You already met sort | uniq -c and awk fields in answering questions from an access log; the patterns come from the previous lesson.

You need bash, gzip, GNU grep, GNU sed and an awk. Tested in a Debian 13 container started with docker run --rm -it python:3.11.14-slim bash (the Python image is built on Debian 13; a Debian or Ubuntu VM also works), with grep 3.11, sed 4.9, gawk 5.2.1 and mawk 1.3.4; apt-get install gawk adds gawk, which step 6 compares with the default mawk. Work in an empty directory and run export LC_ALL=C first, so sorting and character classes behave the same on every machine.

The log format is a shortened version of the common "combined" format, with the request time in seconds added at the end. Split on spaces, field 1 is the client address, fields 2 and 3 the time and time zone, fields 4 to 6 the quoted request (method, path, protocol), field 7 the status, field 8 the response size in bytes and field 9 the time taken in seconds. The addresses come from the documentation ranges of RFC 5737, so they belong to no real client.

One log line, field by field (awk splits on spaces)
203.0.113.7 [24/Nov/2026:09:58:12 +0000] "GET /api/orders/1842 HTTP/1.1" 200 512 0.084
$1          $2                    $3     $4   $5               $6        $7  $8  $9

02. Step 1: Create the logs

Paste the block. It saves a script, make-logs.sh, and runs it. The script writes three small log files into logs/, compresses the two older ones the way logrotate would, and lists the result.

Bash · write and run make-logs.sh
cat > make-logs.sh <<'EOF'
mkdir -p logs && cd logs
cat > access.log-20261124 <<'LOG'
203.0.113.7 [24/Nov/2026:09:58:12 +0000] "GET /api/orders/1842 HTTP/1.1" 200 512 0.084
198.51.100.23 [24/Nov/2026:09:59:40 +0000] "GET /api/items?p=2 HTTP/1.1" 200 2048 0.120
203.0.113.7 [24/Nov/2026:10:01:03 +0000] "POST /api/orders HTTP/1.1" 201 96 0.410
192.0.2.55 [24/Nov/2026:10:02:19 +0000] "GET /api/orders/77 HTTP/1.1" 404 41 0.012
198.51.100.23 [24/Nov/2026:10:15:51 +0000] "GET /api/items/9 HTTP/1.1" 200 733 0.095
203.0.113.7 [24/Nov/2026:10:40:00 +0000] "GET /api/orders/1842 HTTP/1.1" 500 87 2.950
LOG
cat > access.log-20261125 <<'LOG'
192.0.2.55 [25/Nov/2026:09:05:44 +0000] "GET /api/items?p=1 HTTP/1.1" 200 2051 0.133
203.0.113.7 [25/Nov/2026:09:12:30 +0000] "GET /api/orders/1900 HTTP/1.1" 200 498 0.077
198.51.100.23 [25/Nov/2026:09:30:02 +0000] "POST /api/orders HTTP/1.1" 201 96 0.388
192.0.2.55 [25/Nov/2026:09:31:10 +0000] "POST /api/login HTTP/1.1" 401 33 0.051
192.0.2.55 [25/Nov/2026:09:31:12 +0000] "POST /api/login HTTP/1.1" 401 33 0.049
192.0.2.55 [25/Nov/2026:09:31:15 +0000] "POST /api/login HTTP/1.1" 200 120 0.062
203.0.113.7 [25/Nov/2026:10:02:48 +0000] "GET /api/orders/1900 HTTP/1.1" 502 0 3.004
LOG
cat > access.log <<'LOG'
198.51.100.23 [26/Nov/2026:09:01:07 +0000] "GET /api/items/9 HTTP/1.1" 200 733 0.101
203.0.113.7 [26/Nov/2026:09:20:33 +0000] "GET /api/orders/2001 HTTP/1.1" 200 505 0.091
192.0.2.55 [26/Nov/2026:09:44:09 +0000] "-" 400 0 0.000
203.0.113.7 [26/Nov/2026:10:05:12 +0000] "POST /api/orders HTTP/1.1" 201 96 0.402
198.51.100.23 [26/Nov/2026:10:06:40 +0000] "GET /api/orders/2001 HTTP/1.1" 500 87 2.871
LOG
gzip -n access.log-20261124 access.log-20261125
ls -1
EOF
bash make-logs.sh
Expected output
access.log
access.log-20261124.gz
access.log-20261125.gz

03. Step 2: Read plain and compressed files in one stream

zcat -f decompresses gzip files and passes any other file through unchanged, so one command reads all three. List the files oldest first, so that later output reads in time order. head lets you look at real lines before you write patterns for them. Stay in the logs directory for the rest of the lab.

Bash · from the directory where you ran step 1
cd logs
export LC_ALL=C
zcat -f access.log-*.gz access.log | wc -l
zcat -f access.log-*.gz access.log | head -n 2
Expected output
18
203.0.113.7 [24/Nov/2026:09:58:12 +0000] "GET /api/orders/1842 HTTP/1.1" 200 512 0.084
198.51.100.23 [24/Nov/2026:09:59:40 +0000] "GET /api/items?p=2 HTTP/1.1" 200 2048 0.120

04. Step 3: Validate the format before you count anything

Field numbers only mean something if every line has the shape you assume. Write one anchored ERE for a whole well-formed line, count how many lines match, and print the ones that do not, with line numbers (-n). Predict first: look at the 18 lines from step 1 and decide how many will fail and why.

The pattern reads: an address made of digits and dots, a bracketed time, a quoted request of method, path and protocol, a three-digit status, a byte count and a decimal time. [^]]+ means "one or more characters that are not ]"; a ] placed first in a bracket expression is taken literally.

Bash · keep good lines, show rejected ones
LINE='^[0-9.]+ \[[^]]+\] "[A-Z]+ [^ "]+ HTTP/[0-9.]+" [0-9]{3} [0-9]+ [0-9.]+$'
zcat -f access.log-*.gz access.log > all.log
grep -cE "$LINE" all.log
grep -vnE "$LINE" all.log
grep -E "$LINE" all.log > clean.log
Expected output
17
16:192.0.2.55 [26/Nov/2026:09:44:09 +0000] "-" 400 0 0.000

One line fails: a client sent something that was not HTTP, and the server logged the request as "-". The request is one field instead of three, so every later field moves two places left: the status is field 5, the byte count 0 is field 6, and a careless $7 would have counted the request time 0.000 as a status. Keep the rejects visible: a report should say "17 of 18 lines parsed", not hide the 18th. In a real incident a sudden rise in rejects is itself a finding (a scanner, a broken client, or a changed log format).

05. Step 4: Extract fields with grep -o

grep -oE prints only the matched part, one match per line, which turns a pattern into a quick extractor. First count methods (tr -d deletes the quote and the space), then count only client and server errors (4xx and 5xx). The second pattern includes the closing quote and the spaces around the status so that it cannot match a byte count such as 404 elsewhere on the line; sed then strips those extra characters.

Bash · methods, then error statuses
grep -oE '"[A-Z]+ ' clean.log | tr -d '" ' | sort | uniq -c
grep -oE '" [45][0-9]{2} ' clean.log | sed -E 's/" ([0-9]+) /\1/' | sort | uniq -c
Expected output
     11 GET
      6 POST
      2 401
      1 404
      2 500
      1 502

06. Step 5: Normalise paths so equal things count together

/api/orders/1842 and /api/orders/1900 are the same endpoint with different IDs. Counted raw, every order would be its own "endpoint" and nothing would look slow. Two sed substitutions fix that: drop the query string, then replace every numeric path segment with :id. The ( |/) group keeps the character after the number, and \1 puts it back.

Bash · normalise, then list distinct requests
sed -E 's#\?[^ ]*##; s#/[0-9]+( |/)#/:id\1#g' clean.log > norm.log
cut -d'"' -f2 norm.log | sort | uniq -c
Expected output
      2 GET /api/items HTTP/1.1
      2 GET /api/items/:id HTTP/1.1
      7 GET /api/orders/:id HTTP/1.1
      3 POST /api/login HTTP/1.1
      3 POST /api/orders HTTP/1.1

Using # as the s delimiter avoids escaping every / in the path. If your API also uses UUIDs or hex IDs, the number pattern will miss them; extend it for your own format and re-run step 3 and this step to check.

07. Step 6: Requests per status per hour with an associative array

In awk, n[key]++ creates the entry the first time a key appears and adds one each time after. Build the key from the hour, the first 14 characters of field 2 after the [, and the status, which is the third field from the end ($(NF-2), where NF is the number of fields). Print the table in the END block, which runs once after the last line.

Predict: awk loops over an array with for (k in n). The block stores the program in a shell variable, prog, and runs it with gawk and with mawk, keeping only the first three lines of each. Will both awks print the same three lines?

Bash · the same program in two awks, without sort
prog='{ n[substr($2, 2, 14) " " $(NF-2)]++ } END { for (k in n) print k, n[k] }'
gawk "$prog" norm.log | head -n 3
mawk "$prog" norm.log | head -n 3
Expected output (gawk 5.2.1, then mawk 1.3.4; other versions may differ)
25/Nov/2026:10 502 1
24/Nov/2026:10 200 1
24/Nov/2026:10 404 1
24/Nov/2026:10 500 1
26/Nov/2026:10 500 1
26/Nov/2026:10 201 1

Different orders, same counts. POSIX leaves the order of for (k in …) unspecified, and each awk walks its own hash table. Never rely on it: pipe the result through sort. Here the key starts with the day, so a plain sort is chronological within one month; for logs that cross a month, sort on a numeric date such as 20261124 instead.

Bash · sorted per-hour table
awk "$prog" norm.log | sort
Expected output
24/Nov/2026:09 200 2
24/Nov/2026:10 200 1
24/Nov/2026:10 201 1
24/Nov/2026:10 404 1
24/Nov/2026:10 500 1
25/Nov/2026:09 200 3
25/Nov/2026:09 201 1
25/Nov/2026:09 401 2
25/Nov/2026:10 502 1
26/Nov/2026:09 200 2
26/Nov/2026:10 201 1
26/Nov/2026:10 500 1

08. Step 7: The busiest clients, and who they are

Count per address, print with a fixed-width number, and sort by count (descending, numeric) and then by address, so ties always come out in the same order. Then join the result with a small table of known clients. join needs both inputs sorted on the joined field; -a 1 -e unknown keeps addresses that have no owner and fills the gap with "unknown", and -o picks the output columns (0 is the join field).

Bash · top clients, then join with an owners table
awk '{ n[$1]++ } END { for (ip in n) printf "%5d %s\n", n[ip], ip }' norm.log |
  sort -k1,1nr -k2,2 | head -n 10 | tee top.txt
printf '203.0.113.7 shop-web\n198.51.100.23 batch-jobs\n' | sort > owners.txt
sort -k2,2 top.txt | join -1 2 -2 1 -a 1 -e unknown -o 1.1,0,2.2 - owners.txt |
  sort -k1,1nr -k2,2
Expected output
    7 203.0.113.7
    5 192.0.2.55
    5 198.51.100.23
7 203.0.113.7 shop-web
5 192.0.2.55 unknown
5 198.51.100.23 batch-jobs

09. Step 8: The slowest endpoints

Now keep three arrays with the same key: a count, a sum and a maximum of the last field. $NF + 0 forces a number. printf aligns the columns so the table can be read at a glance and sorted reliably. Predict: which endpoint has the highest maximum, and is it also the one with the highest average?

Bash · count, average and maximum request time per endpoint
awk '{ ep = substr($4, 2) " " $5; t = $NF + 0; c[ep]++; sum[ep] += t
       if (t > max[ep]) max[ep] = t }
     END { for (ep in c)
             printf "%-20s %3d %6.3f %6.3f\n", ep, c[ep], sum[ep] / c[ep], max[ep] }' \
  norm.log | sort -k5,5nr | head -n 5
Expected output
GET /api/orders/:id    7  1.298  3.004
POST /api/orders       3  0.400  0.410
GET /api/items         2  0.127  0.133
GET /api/items/:id     2  0.098  0.101
POST /api/login        3  0.054  0.062

GET /api/orders/:id wins on both, but look closer: four of its seven requests took under 0.1 s and three took about 3 s, and those three are the 500 and 502 responses. An average hides that split. Before you report "orders are slow", check whether the slow requests are the failing ones, for example with awk '$5 ~ /orders/ && $NF > 1' norm.log.

10. Step 9: Save the report as CSV

A CSV file can go into a spreadsheet or a ticket. tee writes the file and still shows the stream, so you can see the tail while saving. The header line goes first, outside the sort.

Bash · write report.csv
{ echo 'hour,status,requests'
  awk '{ n[substr($2, 2, 14) "," $(NF-2)]++ } END { for (k in n) print k "," n[k] }' \
    norm.log | sort
} | tee report.csv | tail -n 3
wc -l report.csv
Expected output
26/Nov/2026:09,200,2
26/Nov/2026:10,201,1
26/Nov/2026:10,500,1
13 report.csv

11. Check your understanding

Practice check · 3 questions

Parsing, arrays and joins

Answer from what you saw in the lab.

Q1. Without step 3, you count statuses with `awk '{ n[$7]++ } END { for (s in n) print s, n[s] }' all.log`. Which extra "status" appears in the output?
Q2. A colleague's report prints `for (k in n)` output without `sort`. On their laptop the rows come out in date order. What should you expect on a server with a different awk?
Q3. The check suggested after step 8, `awk '$5 ~ /orders/ && $NF > 1' norm.log`, prints: 203.0.113.7 [24/Nov/2026:10:40:00 +0000] "GET /api/orders/:id HTTP/1.1" 500 87 2.950 203.0.113.7 [25/Nov/2026:10:02:48 +0000] "GET /api/orders/:id HTTP/1.1" 502 0 3.004 198.51.100.23 [26/Nov/2026:10:06:40 +0000] "GET /api/orders/:id HTTP/1.1" 500 87 2.871 Which statement does this output support?
Practice only: not graded, not saved, not evidence.

12. Apply it

Extend the lab towards the skill's logreport.sh practice task. Add a fourth question to the report: for each hour, what share of requests were 5xx errors? Compute it in one awk program with two arrays (total per hour and errors per hour) and print the hour and a percentage with printf "%.1f". Then point your pipeline at a directory of real compressed logs, for example a copy of /var/log/nginx from a test VM, adapt the step 3 pattern to that format, and record how many lines it rejects and why.

13. Review prompt

Without looking back, explain why the lab validated the format before counting, and what would have gone wrong in step 6 and step 8 without the normalisation in step 5. Then explain why the output of an awk for (k in …) loop must be sorted, and how you would make ties in a top-10 list come out the same on every run.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check