
Recall first from sed and awk: the basics
- sed edits a stream line by line through the pattern space; it prints by default and only changes the file with -i.
- s/old/new/ replaces the first match per line; g replaces all, and a number selects one occurrence.
- sed addresses are line numbers, regexes, ranges and $, written before a command such as p or d.
awk fields and separators
2 min readThe first lesson on this topic introduced awk's records and fields under the default whitespace separator. This lesson answers how awk's separators, built-in variables and BEGIN/END parse real log files.
The default field separator is whitespace, but many files use another character. /etc/passwd is colon-delimited, and CSV data is comma-delimited. awk switches separator with the -F option on the command line, or by assigning FS inside a BEGIN block.
awk -F: '{print $1, $NF}' /etc/passwd # username and shell
awk -F, '{print $1, $3}' data.csv # first and third columns
The same effect comes from FS in BEGIN, which also lets you use a regular expression as the separator, such as FS="[ ,]+" to split on any run of spaces or commas.
awk 'BEGIN{FS=":"} {print $1}' /etc/passwd
The output side has its own variable. OFS is the string print inserts between comma-separated arguments, a single space by default. Setting it reformats output without touching the input.
awk -F: 'BEGIN{OFS=" :: "} {print $1, $NF}' /etc/passwd
For shell scripts, -v passes a shell variable into awk before it runs, which is how a script parameter reaches the program.
n=2
awk -v col="$n" '{print $col}' data
One precision note: awk's field splitting has no concept of quoting. A CSV field that itself contains a comma, such as "Smith, John", is split into two fields by awk, because awk only sees the commas. Real CSV files with embedded delimiters need a CSV-aware tool; awk is the right choice for the plain, unquoted tabular text that logs and config files are made of.
learner@embeddex:~/lab$ # -F: splits on colons, so $1 is the username
learner@embeddex:~/lab$ awk -F: '{print $1}' /etc/passwd | head -3
root
daemon
bin
learner@embeddex:~/lab$ # $NF is the last colon field, the login shell
learner@embeddex:~/lab$ awk -F: '{print $1, $NF}' /etc/passwd | head -3
root /bin/bash
daemon /usr/sbin/nologin
bin /usr/sbin/nologin
learner@embeddex:~/lab$ # OFS sets what print inserts between fields on output
learner@embeddex:~/lab$ awk -F: 'BEGIN{OFS=" :: "} {print $1, $NF}' /etc/passwd | head -3
root :: /bin/bash
daemon :: /usr/sbin/nologin
bin :: /usr/sbin/nologinawk built-in variables and BEGIN/END
3 min readThe pattern-action rules run once per record, but two special patterns break that rhythm. BEGIN runs before the first record is read, and END runs after the last. That is where you set FS, print headers, zero counters, and finally print totals and averages.
Try it below: step awk through its three phases by clicking the events.
awk also ships a set of built-in variables that track the data as it flows.
a variable awk maintains automatically, such as NR, NF and FS, reflecting the current record or configuration
NRis the number of records read so far, across all input files.FNRis the number of records read in the current file, reset to 1 when a new file starts.NFis the number of fields in the current record.FSandOFSare the input and output field separators.RSandORSare the input and output record separators, a newline by default.
The count, sum and average pattern is the most common use of BEGIN and END:
awk '{ n++; sum += $1 } END { print n, sum, sum/n }' nums.txt
n++ counts records, sum += $1 accumulates the first field, and END prints the count, the total, and the average in one go. Adding NR to a report is the same idea:
awk 'BEGIN{FS=":"} {print NR, $1} END{print NR " users"}' /etc/passwd
The difference between NR and FNR only appears with more than one file. Give awk two files and watch FNR restart while NR keeps counting:
awk '{print "FNR=" FNR, "NR=" NR}' a b
FNR resets at each file boundary, which lets a program treat each file independently while NR still knows the grand total. Setting RS to an empty string switches awk into paragraph mode, where records are separated by blank lines instead of newlines, useful for multi-line records such as address blocks.
BEGIN: runs once before any record; set FS, print headers, zero the counters.
Per record: each pattern-action rule runs once per record, in order.
END: runs once after the last record; print totals, averages and footers.
learner@embeddex:~/lab$ # accumulate per record, print the total and average once in END
learner@embeddex:~/lab$ awk '{n++; sum += $1} END {print n, sum, sum/n}' nums.txt
3 60 20
learner@embeddex:~/lab$ # FNR resets per file while NR keeps counting across both
learner@embeddex:~/lab$ awk '{print "FNR=" FNR, "NR=" NR}' a b
FNR=1 NR=1
FNR=2 NR=2
FNR=1 NR=3
FNR=2 NR=4
FNR=3 NR=5
learner@embeddex:~/lab$ # BEGIN prints a header once, before any record
learner@embeddex:~/lab$ awk 'BEGIN { print "n sum avg" } { n++; sum += $1 } END { print n, sum,
sum/n }' nums.txt
n sum avg
3 60 20Parsing real logs
3 min readReal logs are where awk earns its keep. Three formats cover most of the field.
The syslog and auth.log files share one layout, but the timestamp depends on the release. Ubuntu 24.04's rsyslog writes a single ISO 8601 field, 2026-11-15T04:45:42.918293+02:00 hostname tag[pid]: message, so the timestamp is $1, the host $2 and the tag $3. Older releases, and systems configured with rsyslog's traditional format, write Nov 15 04:45:42 hostname tag[pid]: message, where the timestamp takes three fields and the host is $4. Look at one line with head -1 before you choose field numbers. On Raspberry Pi OS Bookworm there is no /var/log/syslog or auth.log at all unless you install rsyslog; read the journal with journalctl instead.
awk '{print $1, $2}' /var/log/syslog # timestamp and host (Ubuntu 24.04)
sudo awk '/Failed password/ {print $(NF-3)}' /var/log/auth.log | sort | uniq -c | sort -rn
The second command pulls the source address out of each sshd "Failed password" line and ranks the offenders. Counting from the end with $(NF-3) works under both timestamp formats, which is why it is the safer habit. It relies on that message ending in from <ip> port <port> ssh2, which places the address three fields before the end; the shape can change between sshd versions, so treat the column position as fragile and verify it on one line before trusting a whole report.
The Apache access log in the common log format is the classic target. Each line looks like this:
203.0.113.7 - - [10/Oct/2024:13:55:36 +0000] "GET /index.html HTTP/1.1" 200 2326
Split on whitespace, $1 is the client IP, $7 the requested path, $9 the status code, and $10 the response size in bytes. The quoted request line is the trap here: it contains spaces, so the request becomes three fields ($6 is "GET, $7 is /index.html, $8 is HTTP/1.1"). That shifts every later field, which is why the status is $9 and not $7.
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head # top IPs
awk '{sum += $10} END {print sum}' access.log # total bytes
awk '{print $7}' access.log | sort | uniq -c | sort -rn | head # top pages
awk '$9 == 404 {print $7}' access.log # missing pages
awk '$10 > 100000 {print $7, $10}' access.log # big responses
awk streams these reports line by line, so a multi-gigabyte log is never held in memory, only the running totals. That streaming property matters on a board with half a gigabyte of RAM.
1extract the field
For a per-status-code report, first name the field you care about, $9.
2accumulate with an array
Build the report with an associative array, previewing the next section:
awk '{count[$9]++; bytes[$9] += $10}
END {for (s in count) print s, count[s], bytes[s]}' access.log
3format the report with printf
printf gives exact columns where print gives rough spacing, using the same specifiers as C: %d for integers, %f for floats, %s for strings, with a width such as %-15s to left-align.
awk '{count[$9]++; bytes[$9] += $10}
END {for (s in count) printf "%-4s %6d %10d\n", s, count[s], bytes[s]}' access.log
/var/log/auth.log and an Apache access log are usually root-owned, so prefix the command with sudo. On the board, if the report uses gawk-only features, install gawk or rewrite it with plain awk; BusyBox awk and mawk both handle the counting and summing above, which is most of what a per-status report needs.
Key takeaways
- awk splits each record into fields on whitespace by default; -F or FS sets the separator, OFS sets the output one.
- BEGIN and END run before and after the record loop, the home of headers, totals and averages.
- In the Apache common log format the quoted request contains spaces, so the status code is $9 and the path is $7.
- awk processes a log one record at a time, keeping only running totals, so a multi-gigabyte file never sits in memory.
Reflect
- Explain to a colleague, in two sentences: use BEGIN and END with NR, NF, FNR, FS, OFS, RS and ORS to sum, count and average data.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
Official documentation first. Links checked when the lesson was published.