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
On this page
- Goal and setup
- Step 1: Create the logs
- Step 2: Read plain and compressed files in one stream
- Step 3: Validate the format before you count anything
- Step 4: Extract fields with grep -o
- Step 5: Normalise paths so equal things count together
- Step 6: Requests per status per hour with an associative array
- Step 7: The busiest clients, and who they are
- Step 8: The slowest endpoints
- Step 9: Save the report as CSV
- Check your understanding
- Apply it
- Review prompt
Lessons of Advanced Shell & Text Processing
- Patterns that travel: regular expressions in grep, sed and awk Concept · 25 min
- Lab: from a raw access log to a report with grep, sed and awk Lab · 30 min
- Bash beyond the basics: expansions, arrays, here-documents and process substitution Worked example · 25 min
- When a script misbehaves: tracing, syntax checks, safe input and portability to dash Worked example · 20 min
- Lab: living on a remote server - editors, sudoedit, startup files, job control and tmux Lab · 30 min
- Check: shell fluency tasks and a log-report script to repair Knowledge check · 10 questions
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.
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 $902. 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.
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.shaccess.log
access.log-20261124.gz
access.log-20261125.gz03. 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.
cd logs
export LC_ALL=C
zcat -f access.log-*.gz access.log | wc -l
zcat -f access.log-*.gz access.log | head -n 218
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.12004. 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.
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.log17
16:192.0.2.55 [26/Nov/2026:09:44:09 +0000] "-" 400 0 0.000One 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.
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 11 GET
6 POST
2 401
1 404
2 500
1 50206. 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.
sed -E 's#\?[^ ]*##; s#/[0-9]+( |/)#/:id\1#g' clean.log > norm.log
cut -d'"' -f2 norm.log | sort | uniq -c 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.1Using # 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?
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 325/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 1Different 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.
awk "$prog" norm.log | sort24/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 108. 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).
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 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-jobs09. 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?
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 5GET /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.062GET /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.
{ 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.csv26/Nov/2026:09,200,2
26/Nov/2026:10,201,1
26/Nov/2026:10,500,1
13 report.csv11. Check your understanding
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.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.