Bash Hour 5: Text and Data Processing

Turn “logs, CSV, JSON, YAML, and a pile of oddly named files” into data you can query: grep to find, sed to edit, awk to compute, find + xargs for batch work, sort/uniq/join for set operations, jq/yq for structured data, and finally add a new logs report opsctl subcommand
Bash 5.3GNU grep 3.12GNU sed 4.9gawk 5.3.2 / mawk 1.3.4jq 1.8yq v4.54 (mikefarah)Ubuntu 26.04 LTSVerified 2026-11-17
Overall learning goals
  • Tell apart BRE / ERE / PCRE the three regex “dialects”; know grep,grep -E,grep -P,sed,sed -E,awk,[[ =~ ]] which to use where; be able to use them to -o,-c,-F,-w,-r handle everyday queries.
  • Understand the sed execution cycle (read into pattern space → match address → run commands → auto-print), and can write s///, addresses and ranges,-n … p, and write in-place edits that work on both GNU and BSD/macOS.
  • Understand the awk record / field model (RS/FS/NR/NF/$0…$NF),pattern { action }, associative arrays and END in the printf reports; know the differences between gawk and mawk.
  • Use find -print0 | xargs -0,find -exec … {} +,while IFS= read -r -d '' handle safely filenames containing spaces, newlines or leading dashes.
  • Use sort/uniq/join/comm/cut/paste for “set operations”, and understand why scripts must write LC_ALL=C (Ubuntu 26.04's Rust coreutils makes this matter more).
  • Use jq and yq (mikefarah v4) to read and write inventory.json and config.yaml; know CSV's limits (quoted commas), and when to switch to Python csv or Miller (mlr).
  • Complete the running project: opsctl logs report <file> (lib/cmd_logs.sh in cmd::logs) — a single awk pass that prints the top paths, status-code distribution and 5xx error rate.

1-hour time allocation table

#TimeModuleCore contentAnimation / interactionLab
0Before classSetup: log, CSV, JSON, YAML datasetsCheck tool versions (grep/sed/awk/jq/yq), generate data with Lesson 1's make-data.sh and verify cksum, confirm opsctl v0.2Environment self-check listGenerate ~/bashlab/data/
100–06grep and regular expressions (BRE / ERE / PCRE)metacharacter differences across the three dialects,-o -c -F -w -E -P,egrep deprecated syntax,LC_ALL=C speed-up tips;how one pattern is interpreted by each dialectcount 5xx responses and extract IPs and paths from access.log
206–13sed: substitution, addresses and in-place editingpattern space and hold space,s/// flags, line-number/regex/range addresses,-n+p,-i the GNU/BSD differences insed execution cycle, line-by-line animationlog redaction, config rewriting (with backup)
313–21awk: fields, patterns and aggregate reportsrecords and fields,FS/OFS/NR/NF, patterns, associative arrays,printf,-v passing variables, gawk vs mawkCore animation: awk splitting fields line by line and updating an associative arraystatus-code distribution, per-IP traffic, slow-request report
421–28find, xargs and safe filename handlingfind expressions,-print0/xargs -0,-exec {} +,--,read -d '',-P concurrencyCore animation: find -print0 | xargs -0 byte stream and argv batchingRun batch operations in data/files/ on the oddly named files
528–35Sorting and set operationssort -k -t -n -V -u,uniq -c,join,comm,cut,paste, locale and Rust coreutilssort | uniq -c pipeline + comm three columns“inventory vs actual” differences, IP-to-hostname mapping
635–42JSON and YAML: jq and yqjq filters,-r/--arg/@tsv/@csv,select/map/group_by; yq v4 read/write,-i,strenv, format conversionvalue flow through a jq filter pipelinecount hosts per environment, edit config.yaml
742–50CSV and the limits of structured dataRFC 4180, quoted commas,cut/awk -F, why it breaks,gawk --csv, Python csv, Millernaive splitting vs a character-by-character CSV state machineParse correctly the "bastion, jump"
850–60opsctl logs: log analysis reportslib/cmd_logs.sh, argument parsing, single-pass awk program, output format, exit codes, performanceexecution flow of one report run + interactive troubleshooting treeImplement and run opsctl logs report data/access.log
—After classCheat sheet · Capstone lab“Incident review data pack”: answer 6 operations questions from logs, inventory, config and filesFinal quiz (12 questions)Capstone lab: 6 steps

Knowledge Coverage Matrix

Target skillM1M2M3M4M5M6M7M8Key commands / objectsLab
Regex dialects✓✓✓··✓·✓grep -E/-P,sed -E, awk ERE, jq test()M1, M2
Stream editing and redaction·✓✓✓····sed -E 's/…/…/g',sed -i.bakM2
Field processing and aggregation··✓·✓✓✓✓awk '{c[$9]++} END{…}',sort | uniq -cM3, M8
Safe filename handling···✓····-print0,xargs -0,-exec {} +,--M4
Sorting, deduplication and set operations··✓·✓··✓LC_ALL=C sort,comm -3,join -t,M5
JSON / YAML·····✓✓·jq -r '.[] | select(…)',yq -iM6
CSV limits and tool choice··✓·✓✓✓·gawk --csv,python3 -c 'import csv',mlrM7
Portability (GNU/BSD/Rust coreutils)✓✓✓✓✓··✓sed -i.bak, POSIX awk,LC_ALL=C“Troubleshooting” in each module
Running project: opsctl··✓·✓··✓opsctl logs report,cmd::logsM8, capstone lab

Topics excluded from this hour (and where to learn them)

TopicWhy not covered hereWhere to learn
Shell expansion, quoting, pipes and redirection basicsAssumed known for this hourLesson 1 · Linux 8 hours
strict mode, trap, locks, retriesCovered in Lesson 4; used directly hereLesson 4
Calling HTTP APIs, deployment and rollback scriptsbelongs to “automation scenarios”Lesson 6
bats testing, ShellCheck, CIThis hour only defines testable function boundaries; tests are added in Lesson 7Lesson 7
Centralized logging platforms (Loki, Elasticsearch, Azure Monitor / CloudWatch Logs Insights)massive log volumes, long-term retention and query languages are not Shell's strengthsPrometheus & Grafana 8 hours(metrics and alerting)
Complex data cleaning and analysis (pandas, DuckDB, SQL)beyond the scope of “command-line glue”; this hour only covers when to switchModule 7's “when to switch tools” decision table

How to use these materials

10 pages per module
Theory · Diagrams · Animation · Commands · Lab · Production cases · Troubleshooting · Quiz · Audio · Video. Module 3 (awk line-by-line processing) and Module 4 (-print0 | xargs -0 data flow) animations are the core of this hour; play them before doing the lab.
Learning progress
A quiz score of ≥ 70%, or clicking “Mark module complete”, counts toward progress, saved in this browser (cleared on refresh if local storage is disabled).
Chinese audio
The “Audio” page reads the script aloud using the browser's built-in Web Speech API (en-US); without a Chinese voice pack, the script can still be read or passed to a TTS tool.
Version notes The baseline is Ubuntu 26.04 LTS the built-in Bash 5.3, GNU grep 3.12, GNU sed 4.9, findutils 4.10.0, gawk 5.3.2 (install required) / mawk 1.3.4-20260129, jq 1.8.1 (upstream latest 1.8.2). yq refers to Mike Farah's Go version v4 (upstream latest v4.54.3, 2026-11-09). Note that the yq package (3.4.3) is a different project (a Python jq wrapper) with different syntax. Ubuntu 26.04's default sort/cut/uniq/comm/join/paste etc. come from Rust coreutils (uutils 0.8.0), whereas grep, sed, awk, find and xargs are not part of coreutils and remain the original GNU / mawk implementations. macOS ships BSD grep/sed/awk and Bash 3.2; differences are noted separately in each module.

Module 0 · Setup: log, CSV, JSON, YAML datasets (complete before class)

Confirm tool versions, prepare five kinds of sample data under ~/bashlab/data/, and bring opsctl to v0.2
Before class ≈ 10 minBash 5.3 · Ubuntu 26.04No cloud resources · zero cost
Prerequisites
  • CompletedLesson 1(~/bashlab working directory and make-data.sh),Lesson 3(opsctl v0.1 skeleton) andLesson 4(opsctl v0.2: strict mode, trap, logging). If you don't have it, that's fine: starting data and starter code are provided below.
  • Choose any environment: the Linux lesson's linuxlab VM, WSL2 Ubuntu 26.04, macOS + Homebrew (brew install bash gawk gnu-sed grep jq yq), or a container docker run --rm -it -v "$PWD":/work -w /work bash:5.3 (Alpine base; grep/sed/awk are BusyBox builds, so this hour's GNU-only options need apk add grep sed gawk findutils coreutils jq, while yq is downloaded as an official binary as described below).
  • Risk: all “bulk delete / rename” demos in this hour run only inside ~/bashlab/data/files/ and always dry-run first with echo or -print .

Step 1: Confirm tools and versions

bash --version | head -1
grep --version | head -1          # expect GNU grep 3.x (macOS ships BSD grep)
sed --version 2>/dev/null | head -1 || echo "BSD sed (macOS)"
readlink -f "$(command -v awk)"   # Ubuntu: /usr/bin/mawk or /usr/bin/gawk
awk -W version 2>/dev/null | head -1 || awk --version | head -1
find --version | head -1; jq --version
yq --version                      # must show mikefarah/yq … version v4.x
sort --version | head -1          # Ubuntu 26.04: sort (uutils coreutils) 0.8.0
GNU bash, version 5.3.x(1)-release (x86_64-pc-linux-gnu)
grep (GNU grep) 3.12
sed (GNU sed) 4.9
/usr/bin/gawk
GNU Awk 5.3.2, API 4.0, PMA Avon 8-g1, (GNU MPFR 4.2.x, GNU MP 6.3.0)
find (GNU findutils) 4.10.0
jq-1.8.1
yq (https://github.com/mikefarah/yq/) version v4.54.3
sort (uutils coreutils) 0.8.0
sudo apt-get update
sudo apt-get install -y gawk jq miller python3     # gawk makes the awk examples and --csv work; miller provides mlr
# yq: do not apt install yq (that is the Python version). Use the official single binary release:
YQ_VER=v4.54.3
sudo wget -qO /usr/local/bin/yq \
  "https://github.com/mikefarah/yq/releases/download/${YQ_VER}/yq_linux_amd64"
sudo chmod +x /usr/local/bin/yq
yq --version
# or: sudo snap install yq   /   macOS: brew install yq
Why pin versions? If the CLI tools a script depends on differ across machines, the output can differ too. In production, pin YQ_VER in the install script and verify the checksums file on the release page, rather than using releases/latest.

Step 2: Generate the dataset (make-data.sh from Lesson 1)

All commands in this hour run on data that the Lesson 1 setup pageprovides ~/bashlab/make-data.sh generates. This script is deterministic (fixed seed, does not read the system clock): any machine produces byte-identical files, so the “actual output” in this hour should match the numbers you see exactly. Don't have this script yet? Go back to Lesson 1, copy it (about 170 lines), then run:

bash ~/bashlab/make-data.sh          # every run deletes and rebuilds ~/bashlab/data
cd ~/bashlab/data
cksum access.log servers.csv inventory.json config.yaml
ls -b files
make-data.sh: generated /home/labadmin/bashlab/data
  access.log       611 lines
  servers.csv       13 lines (including header)
  inventory.json    12 objects
  config.yaml     opsctl sample config
  files/            15 oddly named files
80306651 79109 access.log
3087317886 526 servers.csv
3924293688 1199 inventory.json
1138550665 787 config.yaml
--verbose.log
-n
[draft]\ notes.md
café-ünïcode.txt
it's.txt
line1\nline2.txt
price\ $5.txt
report\ 2026.txt
say\ "hi".txt
star*.txt
sub\ dir
tab\there.txt
trailing-space.txt\ 
two\ \ spaces.txt

ls -b Entries starting with a dot are not shown .hidden.txt,sub dir/ also contains nested file.log, 15 files in total. A cksum mismatch is most often caused by CRLF line endings or curly quotes slipping into the copied script.

Data facts used throughout this hour

FileKey points (all from actual output)
access.log611 lines, 17/Nov/2026 10:00:01–10:31:00 UTC, combined format; GET 524 / POST 87; status 200×450, 201×54, 301×12, 302×19, 304×22, 400×11, 401×6, 404×9, 500×12, 502×4, 503×12 (5xx = 28, 4xx = 26); 6 paths: /api/orders 211,/healthz 121,/ 75,/login 74,/api/orders/1042 67,/static/app.js 63; 11 client IPs; lines 151–156 are 198.51.100.23 against /login 's 6 401 responses (brute force); lines 458–461 are 10.20.1.31 with 4 consecutive 502s; line 307's UA contains a single quote and \x22
servers.csvheader name,env,region,ip,role + 12 lines (dev 3 / staging 3 / prod 6); hostnames repeat across environments (web-01 has three instances); line 11 edge-01,…,"web,api" is the boundary case with a quoted comma
inventory.jsonhas the same 12 objects as servers.csv (role is a "web,api" string)
config.yamltop-level opsctl,environments (dev/staging/prod mapping),health,backup,deploy; log_level: info end-of-line comments
files/15 oddly named entries: leading dash (-n,--verbose.log), spaces, two spaces, trailing space, tab, newline, single/double quotes,$,*,[ ], non-ASCII, hidden files, subdirectory with spaces

Step 3: opsctl at v0.2

This hour starts from the state at the end of Lesson 4 ( opsctl v0.2.0 (git tag v0.2.0: strict mode set -Eeuo pipefail + inherit_errexit,util::setup_traps,EX_* constants,util::retry/lock/mktemp_dir/cleanup_add) on adds a new subcommand, using these existing conventions: bin/opsctl auto-discovers lib/cmd_<name>.sh and invokes cmd::<name>,help generated from the file header's # opsctl-summary: comments; lib/log.sh of the log::debug/info/warn/error (writes to stderr); lib/util.sh of the util::die <msg> [code],util::usage_error (exit code 2),util::require_cmd (exit code 3),util::in_list; lib/config.sh of the config::set_flag / config::get <key> <out_var> [src_var] and OPSCTL_DEFAULTS (new keys must be added here, since this list is also the whitelist of valid keys).

Config precedence (Lesson 3): command-line options > environment variables OPSCTL_<KEY> > config file > defaults; when an option overrides a different environment variable value, one line is logged only at -v (debug). If you don't have the results from the previous two lessons, first follow theLesson 3 capstoneto copy v0.1, then followLesson 4“opsctl v0.2” upgrade steps before the Lesson 4 capstone (replace lib/log.sh, append lib/util.sh the v0.2 section of bin/opsctl).

cd ~/bashlab/opsctl
bin/opsctl --version
bin/opsctl help | sed -n '/^Commands:/,$p'
opsctl 0.2.0
Commands:
  config           show effective configuration and where each value came from
  doctor           check bash version, dependencies, data and lock dirs (read-only)
  export           export servers.csv atomically (export servers --out FILE [--env ENV])
  servers          query the server inventory (servers list --env ENV)
  help [COMMAND]   show help for a command

Precedence: flags > environment (OPSCTL_*) > config file > defaults
Runtime env: OPSCTL_LOG_FILE, OPSCTL_LOCK_DIR, RETRY_MAX_DELAY, NO_COLOR
Exit codes: 0 ok, 1 error, 2 usage error, 3 missing dependency

Self-check list

Module 1 · grep and regular expressions (BRE / ERE / PCRE)

00:00 – 06:00 · the same string means different things in three “dialects” — first figure out which one you're using
6 minGNU grep 3.12 · POSIX★★★★★
Learning goals
  • State the differences between BRE, ERE and PCRE in + ? | ( ) { } and \d \b \w and know which one each tool uses by default.
  • Use fluently -E -F -P -o -c -n -w -v -l -q -r -m -A/-B/-C, and explain -c counts “lines”, not “match count”.
  • Know egrep/fgrep deprecated,-P not available everywhere,LC_ALL=C can speed things up significantly, and use exit codes (0/1/2) for conditionals in scripts.
Prerequisites: Lesson 1 quoting rules (always single-quote regexes). Importance:★★★★★

What: grep and regular expressions

grep (the name comes from the ed editor command g/re/p: global / regular expression / print), reads input line by line and uses a regular expression to test each line, writing matching lines to stdout. “Regex” is not one language but a family: POSIX defines basic regular expressions (BRE) (default for grep and sed) and extended regular expressions (ERE) (grep -E,sed -E awk, Bash's [[ =~ ]]); Perl developed the richer PCRE (grep -P, GNU grep 3.8+ is based on PCRE2).

Why: why ops uses it every day

  • First stop: the first thing to do during an incident is usually grep -c ' 500 ' access.log,journalctl -u myapp | grep -i error.
  • Conditions in scripts: if grep -q '^ERROR' "$log"; then …— grep's exit codes 0 (found) / 1 (not found) / 2 (error) are natural booleans.
  • Fast: for patterns without back-references, GNU grep uses a DFA and Boyer–Moore-style skip search, so scanning GB-sized logs is usually faster than awk/Python; -F fixed strings are faster still.

How: differences between the three dialects (the most common pitfalls)

SyntaxBRE (default for grep / sed)ERE (grep -E / sed -E / awk / [[ =~ ]])PCRE (grep -P)
+ ? |ordinary characters; GNU extensions \+ \? \| are quantifiers/alternation (undefined by POSIX)Quantifiers and “or”same as ERE, plus lazy +?, possessive ++
( ),{m,n}ordinary characters; grouping/ranges must be written \( \),\{m,n\}are directly grouping and rangessame as ERE, plus (?:…), named groups, assertions (?=…) (?<=…)
\d \w \s \bundefined by POSIX; GNU supports \w \s \b \< \>,\d not supported (3.8+ warns “stray \ before d” and matches the letter d)same as leftall supported; also \K (discards the already-matched prefix)
character classes[[:digit:]] [[:space:]] [[:alpha:]] (POSIX, portable, locale-dependent)both support
back-references \1supported (disables the DFA fast path)undefined in POSIX ERE, GNU supportssupported

When: which switch to use

ScenarioRecommendedReason
finding a fixed string (containing . ? [ * etc.)grep -Fno metacharacter interpretation, fastest, hardest to get wrong
need + ? | ( ) {n}grep -EPOSIX standard, available in GNU / BSD / BusyBox
need \d, assertions,\K, non-greedygrep -P or switch to awk/perl-P is a GNU extension: macOS's grep and BusyBox don't have it; it may be disabled at compile time
only need to know whether it matchesgrep -qexits at the first match, prints nothing
judge by field (column 9 = 500)awkgrep only matches characters, not columns: grep 500 matches byte count 5000, time 10:05:00
Common misconceptions① “grep -c count matches” — it counts matching lines, so two matches on one line count as 1; to count occurrences use grep -o … | wc -l. ② “egrep is just grep -E, keep using it” — since GNU grep 3.8 egrep/fgrep prints a deprecation warning, so in scripts write grep -E/grep -F. ③ “\d works everywhere” — it doesn't in BRE/ERE; GNU grep treats it as the letter d.
BRE basic regex (POSIX) grep (default)sed (default)ed / vi :s grouping/ranges need a backslash:\( \) \{2\} GNU: \+ \? \| ERE extended regex (POSIX) grep -Esed -E (GNU also accepts -r)awk / gawk / mawkBash [[ $s =~ re ]] + ? | ( ) {n} work directly PCRE (Perl-compatible) grep -P (GNU, PCRE2)perl / python re (similar)jq test()/sub() (Oniguruma) \d \b \K (?=…) (?<=…) non-greedymacOS / BusyBox grep has no -P From left to right: more features, less portability
Figure 1-1: the three regex dialects and the tools that use them (jq uses Oniguruma, with syntax close to PCRE)
file / stdinreads in blocks via read() splits into lines-z: split lines on \0 matcher-F: Boyer–Moore styleBRE/ERE: DFA (falls back when \1 is present)-P: PCRE2 (JIT-capable) option filtering-v -w -x -m lines / -o fragments -c line count / -l filenames exit code 0 / 1 / 2
Figure 1-2: grep data flow. The pattern choice determines the matching algorithm, options determine the output form, and the exit code lets scripts branch

Interactive: same pattern, how is it read across the three dialects?

Pick a pattern and step through its tokens one at a time to see the BRE / ERE / PCRE interpretation; the number of matching lines in each dialect is shown at the end, on access.log (611 lines) (actual output: BRE/ERE use GNU grep, PCRE is computed with the equivalent Python re).

DialectMeaning of current tokenMatching lines
BRE grep—?
ERE grep -E—?
PCRE grep -P—?
Ready: click “Next” to explain tokens one by one.
$ LC_ALL=C grep -c '…' data/access.log

Common options

OptionEffectNotes
-E / -F / -PERE / fixed strings / PCREdefault BRE; -P GNU only
-i -v -w -xignore case / invert / whole word / whole line-w a “word” = letters, digits, underscore
-oprint only the matched fragment, one per linecombined with sort | uniq -c for counting
-c / -l / -Lmatching line count / filenames with matches / filenames without matches-c not the match count
-n -H -hline numbers / with filename / without filenamefilenames shown by default with multiple files
-A n -B n -C ncontext after / before / n lines of context around matchesseparate groups with -- separator
-m n -qat most n matching lines / quiet, exit code onlyexit early on large files
-r --include --exclude-dirrecursively search directories-r do not follow symlinks,-R follow
-e pat -f file --multiple patterns / read patterns from file / end of optionsa pattern starting with - must be used when it starts with -e or --
-z --nullsplit input lines on \0 / output filenames followed by \0and xargs -0 used with (Module 4)
cd ~/bashlab
export LC_ALL=C                      # all statistics in this hour run under the C locale (reason in Module 5)

grep -c '" 5[0-9][0-9] ' data/access.log           # BRE: brackets are also valid in BRE
grep -cE '" 5[0-9]{2} ' data/access.log            # ERE: {2} works directly
grep -c  '" 5[0-9]\{2\} ' data/access.log          # BRE: intervals need backslashes
28
28
28

Why include " and the space? in combined format the status code comes right after the closing quote of the request line (HTTP/1.1" 500 87). See what happens without the quotes:

grep -c ' 50[0-9] ' data/access.log
grep ' 50[0-9] ' data/access.log | grep -v '" 50'
29
203.0.113.99 - - [17/Nov/2026:10:02:36 +0000] "POST /api/orders HTTP/1.1" 201 506 "-" "kube-probe/1.37"

The extra match is line 52: status 201,byte count 506 — it also happens to be “space + 50x + space”. grep only matches characters, not columns; column-based checks belong in awk (Module 3).

# -o + sort | uniq -c: who visits most? which “method + path” is most common?
grep -oE '^[0-9.]+' data/access.log | sort | uniq -c | sort -k1,1nr -k2
grep -oE '"(GET|POST) [^ ]+' data/access.log | sort | uniq -c | sort -k1,1nr -k2
     75 198.51.100.23
     69 203.0.113.99
     64 10.10.1.22
     64 203.0.113.7
     63 172.16.5.4
     61 192.0.2.10
     58 10.10.1.21
     54 192.0.2.11
     51 10.20.1.31
     51 192.0.2.12
      1 192.0.2.66
    149 "GET /api/orders
    121 "GET /healthz
     75 "GET /
     67 "GET /api/orders/1042
     63 "GET /static/app.js
     62 "POST /api/orders
     49 "GET /login
     25 "POST /login
# -P + \K: keep only the path itself, not the "GET in front of it
grep -oP '"(?:GET|POST) \K[^ ?]+' data/access.log | sort | uniq -c | sort -k1,1nr -k2
# Equivalent for systems without -P (macOS, BusyBox):
grep -oE '"(GET|POST) [^ ?]+' data/access.log | cut -d' ' -f2 | sort | uniq -c | sort -k1,1nr -k2
    211 /api/orders
    121 /healthz
     75 /
     74 /login
     67 /api/orders/1042
     63 /static/app.js
# -F: ? and . in the pattern are literals
grep -cE '?' data/access.log          # 611! A leading ? is undefined in ERE; GNU treats it as “optional empty” → matches every line
grep -cF '?' data/access.log          # 0  ← this is the real “lines containing a question mark” (no query strings in this data)
grep -cF '1.37' data/access.log       # 218 (kube-probe/1.37); without -F it is 219: . matches any character, so one extra line matches

# exit code as a boolean
if grep -q '" 401 ' data/access.log; then echo "Login failures found"; fi
grep -q nosuchthing data/access.log; echo "rc=$?"          # 1 = not found
grep -q x /nonexistent 2>/dev/null; echo "rc=$?"           # 2 = error
611
0
218
Login failures found
rc=1
rc=2
# context, match limits, recursion
grep -n -A1 '" 502 ' data/access.log | head -4  # 502 and the line after it (from line 458)
grep -m2 -n healthz data/access.log            # only the first two matching lines
grep -rn --include='*.sh' 'set -euo pipefail' ~/bashlab/opsctl
grep -rlZ 'TODO' ~/bashlab/opsctl | xargs -0 -r ls -l   # -Z: filenames end with \0
How to verify / common errors / production uses Verify: first run with grep -n to see which lines match, then add -c or -o. Common errors: pattern not single-quoted, so the shell expands it (grep *.log); pattern starting with - (grep -e '-v' file). Production use: health checks curl -fsS … | grep -q '"status":"ok"', blocking secret commits in CI git diff --cached | grep -E 'AKIA[0-9A-Z]{16}'.

Performance: LC_ALL=C

# In a UTF-8 locale, [a-z], -i and \w must handle multibyte characters; in the C locale they work on bytes, often several times faster
time grep -c 'orders' big.log
time LC_ALL=C grep -c 'orders' big.log

Note: LC_ALL=C under [[:alpha:]] no longer matches non-ASCII letters such as Chinese; to process UTF-8 text by character (e.g. Chinese logs), use LC_ALL=C.UTF-8. grep -P only supports single-byte and UTF-8 locales; in other locales it reports “-P supports only unibyte and UTF-8 locales”.

Lab 1: answer 5 questions with grep

Goal: using only grep (plus sort/uniq/wc/paste), from data/access.log get a preliminary incident assessment. Environment:~/bashlab, data generated by make-data.sh. Cleanup: None (read-only).

How many 5xx?
cd ~/bashlab && export LC_ALL=C
grep -cE '" 5[0-9]{2} ' data/access.log
28
Which IP and which request do all the 5xx responses come from?
grep -E '" 5[0-9]{2} ' data/access.log | grep -oE '^[0-9.]+|"(GET|POST) [^ ]+' | paste - - | sort | uniq -c | sort -k1,1nr | head -4
      7 10.20.1.31	"GET /api/orders
      4 192.0.2.12	"GET /api/orders
      2 10.10.1.21	"GET /api/orders
      2 10.10.1.22	"GET /api/orders

grep -o Each line outputs two fragments (IP and request),paste - - merge every two lines into one (detailed in Module 5).

line count vs match count
grep -c 'Mozilla' data/access.log
grep -o 'Mozilla\|Safari' data/access.log | wc -l     # a line may contain two matches
188
376
Sources of failed logins (401)
grep -F '"POST /login' data/access.log | grep -F '" 401 ' | grep -oE '^[0-9.]+' | sort -u
198.51.100.23

All 6 401s come from it, concentrated in lines 151–156 (grep -n '" 401 ' data/access.log) — a typical brute-force pattern.

Verify -P availability and write fallback logic
if echo x1 | grep -qP 'x\d' 2>/dev/null; then
  echo "grep -P available"
else
  echo "grep -P not available: use grep -E '[0-9]' or awk" >&2
fi
grep -P available

Acceptance

Case 1: an alert script turned “HTTP/1.1" 500” into “500”

Problem: counts per minute grep -c ' 50[0-9] ' access.log, successful requests whose byte count happens to be 500–509 were also counted (there is one in this data set 201 506), causing false alerts during traffic peaks. Fix: switch to column-based checks: awk '$9 ~ /^5/' (Module 3), or at least anchor the context grep -cE '" 5[0-9]{2} '. Limitations: context anchoring depends on the log format; if the format changes (e.g. JSON logs), switch to jq.

Case 2: secret scanning in CI

Problem: Need to block AWS access keys and private key files from being committed before merge. Fix:

if git diff --cached -U0 | grep -nE '^\+.*(AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)'; then
  echo "possible secret detected, refusing to commit" >&2; exit 1
fi

Limitations: regex only catches known formats; for real projects use gitleaks / GitHub Secret Scanning (see GitHub 8 hours).

Case 3: grep -P in a cross-platform script

Problem: A developer's deployment script failed on macOS: grep: invalid option -- P. Fix: the script uses only POSIX -E/-F; where \K is needed, switch to sed -E 's/…(capture)…/\1/' or awk; or at the top of the script util::require_cmd ggrep and warn brew install grep. Limitations: maintaining two sets of syntax is costly; prefer portable syntax.

grep: warning: stray \ before d

Cause: wrote \d (PCRE syntax) in BRE/ERE. Since GNU grep 3.8, a meaningless backslash triggers a warning and is matched as the literal letter d — the results are completely wrong.

grep -E '\d+' data/access.log | head -1     # matches lines containing the letter d
grep -E '[0-9]+' data/access.log | head -1   # correct: POSIX syntax
grep -E '[[:digit:]]+' data/access.log | head -1

Fix: use [0-9] or [[:digit:]]; when PCRE is really needed, use -P.

egrep: warning: egrep is obsolescent

Cause: since GNU grep 3.8 (2022-09) egrep/fgrep is only a wrapper script that prints a warning. Diagnosis:grep -rn -E '\b[ef]grep\b' scripts/. Fix: replace with grep -E / grep -F; CI jobs that treat stderr as a failure will error because of this.

grep: -P supports only unibyte and UTF-8 locales

Cause: the current locale is neither single-byte (such as C) nor UTF-8 (for example, some Windows/MSYS setups or a locale that was never generated). Diagnosis:locale,locale -a. Fix:LC_ALL=C.UTF-8 grep -P … or LC_ALL=C grep -P ….

grep: invalid option -- 'P' / grep: unrecognized option '--include'

Cause: running on BSD grep (macOS) or BusyBox grep (Alpine containers). Diagnosis:grep --version (BSD/BusyBox output is completely different or errors out). Fix: macOS brew install grep then use ggrep; Alpine apk add grep; or rewrite using POSIX options.

“Binary file access.log matches”

Cause: the file contains NUL bytes or an encoding that is invalid in the current locale, so grep treats it as binary and prints only a one-line notice. Diagnosis:grep -c $'\x00' file not feasible (arguments cannot contain NUL); use tr -d '\000' < f | cmp - f or file f. Fix:grep -a (treat as text), or LC_ALL=C grep (for encoding problems).

Command questions

1. Count how many times each status code appears in access.log, using only grep + sort + uniq.
LC_ALL=C grep -oE '" [0-9]{3} ' data/access.log | tr -d '" ' | sort | uniq -c | sort -k1,1nr
2. List all .sh files under ~/bashlab/opsctl that do not contain “set -euo pipefail”.
grep -rL --include='*.sh' -F 'set -euo pipefail' ~/bashlab/opsctl

Note: lib/*.sh files are libraries that get sourced, so they should not set strict mode themselves (the entry point does).

Scenario analysis question

A colleague wrote if grep "$user" /etc/passwd; then … to check whether a user exists; when the username is -v the script misbehaves; when the username is bob also bobby it still counts as existing. How do you fix it?

① a pattern starting with - is treated as an option: use grep -e "$user" or grep -- "$user". ② Substring matching: the username is a field, not an arbitrary substring, so anchor it with grep -q "^${user}:", and a . in the username is treated as a metacharacter — a better approach is getent passwd "$user" >/dev/null or awk -F: -v u="$user" '$1==u{f=1} END{exit !f}' /etc/passwd. ③ To suppress output, add -q.

Verified instructional videos

▶
Regular Expressions (RegEx) in 100 Seconds — Fireship
English · about 2 minutes · overall impression of regex (mainly JavaScript/PCRE style; note the differences from BRE/ERE)
▶
Where GREP Came From - Computerphile — Computerphile
English · Brian Kernighan explains where grep came from (ed's g/re/p), building the “line-by-line + regex” model

Official documentation

Video storyboard (about 80 seconds)

This courseware cannot generate video/MP3 directly; a storyboard and narration script are provided, which can be passed to a video tool.

Scene 1 · 0–15s
Visual: one line of access.log is enlarged; status 500, byte count 5000 and time 10:50:00 all flash at once.
Narration: finding 500 with grep looks simple, but all three places would match.
Scene 2 · 15–45s
Visual: three side-by-side panels (BRE, ERE, PCRE). The same pattern, “five, bracket zero to nine, brace two”, is read as literal characters or as quantifiers depending on the dialect.
Narration: the same characters mean different things in the three dialects. In BRE, braces are ordinary characters; only in ERE are they quantifiers.
Scene 3 · 45–65s
Visual: grep -o outputs fragments that flow into sort and uniq -c, becoming a ranking.
Narration: the -o flag prints only the matched fragments; combined with sorting and de-duplication, a ranking appears in seconds.
Scene 4 · 65–80s
Visual: three lights for exit codes 0, 1 and 2, corresponding to found, not found, and error.
Narration: in a script, grep's exit code is the condition; use the -q flag to test silently.
or score ≥ 70% on the Quiz

Module 2 · sed: substitution, addresses and in-place editing

06:00 – 13:00 · a small programmable editor that reads a line, changes it and prints it
7 minGNU sed 4.9 · BSD sed comparison★★★★☆
Learning goals
  • Use the model of “pattern space / hold space + execution cycle” to predict sed's output and explain -n,p,d interactions.
  • Write substitutions with group captures, flags (g,N,I,p) and custom delimiters; s/// use line-number, regex,$, range and negated addresses.
  • Write in-place edits that run on both GNU and BSD/macOS, and know -i replaces the inode (affecting hard links, permissions and symlinks).
Prerequisites: BRE/ERE from Module 1. Importance:★★★★☆ (for structured files — JSON/YAML — use jq/yq instead; see Module 6)

What: stream editor

sed (stream editor) processes input line by line running a script. Each line is first read into pattern space; commands in the script check addresses and edit it in turn, and when the script ends (unless you used -n) it automatically prints the pattern space, then starts the next cycle. There is also a hold space (hold space), using h/H/g/G/x to swap them.

Why: when to use sed

  • bulk replacement: change one line in a config, redact logs, bump version numbers in bulk.
  • line range extraction: take logs between two timestamps, lines 100–200 (sed -n '100,200p').
  • cleaning in the middle of a pipeline: strip trailing whitespace, delete comments and blank lines, convert CRLF to LF (sed 's/\r$//').

How: what happens in one cycle

  1. Read the next line (without the newline) into the pattern space; increment the line counter by 1.
  2. Starting from the first command in the script: if the command has an address, check whether the current line matches; if not, skip that command.
  3. Execute commands: s modify the pattern space; d clear the pattern space and start the next cycle immediately (later commands are not executed); p print immediately; q print, then quit.
  4. End of script: without -n , print the pattern space (adding the newline back).
Address syntaxMeaningExample
5,$line 5, last linesed -n '$p'
/re/,\%re%lines matching a regex (a custom delimiter avoids escaping /)sed -n '\%/api/%p'
a,bRange: from the line matching a to the line matching b (b is checked starting from the line after a)/START/,/END/d
addr!negation/^#/!s/foo/bar/
first~step,addr,+N,0,/re/GNU extensions: step, next N lines, first matchsed -n '1~5p'

When: choosing between sed, awk and jq/yq

TaskPreferredReason
regex substitution, deleting lines, extracting line rangessedshortest and fastest
column checks, counting, summing, reportsawksed has no numeric operations or associative arrays
editing JSON / YAML fieldsjq / yqsed does not understand nesting and quotes, so it easily breaks the structure
multi-line, complex state machinesawk / Pythonsed's N/D/hold space is hard to read
Common misconceptions① “sed -i edits the original file in place” — in fact it writes a temp file and then rename() overwrites it; the file's inode changes: hard links break, and editing through a symlink replaces the link with a regular file (GNU uses --follow-symlinks). ② “sed -i '' works everywhere” — this is BSD syntax; on GNU sed, '' is treated as a script and the next argument is treated as a file. ③ “s/a/b/ replaces all a's” — by default only the first in each line; to replace all, add g.
Input streamread line by line Pattern spacecurrent line (without \n)s / y / d / p / n / N Hold spaceh H g G x exchange Script (one command at a time) 1. [address] command address doesn't match → skip2. d → start next cycle immediately3. p → print once immediately4. q → print, then quitend of script → auto-print(-n disables auto-print) Output streamor the temp file of -i
Figure 2-1: sed's two buffers and one cycle: read in → run commands one by one (controlled by addresses) → auto-print
config.yamlinode 1001 sed processing line by linewrites to ./sedXXXXXX rename() overwritesnew inode 2002 -i.bak: original file renamedto config.yaml.bak consequences: hard links break, and a process running tail -fstill reads the old inode; the directory needs write permission
Figure 2-2: in-place editing is not really “in place”: temp file + rename, with side effects

Line-by-line demo of the sed execution cycle

Script: head -5 data/access.log | sed -E '/healthz/d; s/^([0-9]+\.[0-9]+\.[0-9]+)\.[0-9]+/\1.0/' (delete the health-check line, and redact the last octet of the IP to 0). Watch each line enter the pattern space, address tests,d end the cycle early,s modify, auto-print. Tick -n to see what happens.

Input stream
Pattern space
(empty)
Output stream
Ready.
$ head -5 data/access.log | sed -E '/healthz/d; s/^([0-9]+\.[0-9]+\.[0-9]+)\.[0-9]+/\1.0/'

Command overview

CommandEffectExample
s/re/rep/flagssubstitute; & represents the whole match,\1…\9 represents a groups/[0-9]+$/[&]/
Flags g N p I w fileall / Nth / print if substitution succeeded / ignore case (GNU) / write to files/=/:/2
d p q =delete / print / quit / print line numbersed -n '/ERR/='
a i cappend text after / before, replace whole lineGNU one-line form 2i\ text; the portable form is shown below
y/abc/xyz/character-by-character conversion (like tr)y/ABC/abc/
-n -E -e -fturn off auto-print / ERE / multi-part script / read script from filesed -n -E '…p'
-i[SUF] (GNU) / -i SUF (BSD)in-place editing (with optional backup suffix)Portable: -i.bak
-s -z --debugGNU: count separately for each file $ / split lines on \0 / print execution tracesed --debug 's/a/b/' f
cd ~/bashlab && export LC_ALL=C
# 1) redaction: last octet of the IP becomes 0 (ERE + groups + back-reference)
sed -E 's/^([0-9]+\.[0-9]+\.[0-9]+)\.[0-9]+/\1.0/' data/access.log | head -2 | cut -c1-60

# 2) line numbers and $; print the line numbers of matching lines
sed -n '151p;$p' data/access.log | cut -c1-60
sed -n '/" 50[0-9] /=' data/access.log | head -5 | tr '\n' ' '
203.0.113.0 - - [17/Nov/2026:10:00:01 +0000] "GET /healthz H
192.0.2.0 - - [17/Nov/2026:10:00:01 +0000] "GET /api/orders
198.51.100.23 - - [17/Nov/2026:10:08:06 +0000] "POST /login
172.16.5.4 - - [17/Nov/2026:10:31:00 +0000] "GET /api/orders
43 130 136 185 229
# 3) extract “status code path”: -n + s///p prints only lines where the substitution succeeded
sed -E -n 's/.*"(GET|POST) ([^ ?]+).*" ([0-9]{3}) .*/\3 \2/p' data/access.log | head -4

# 4) range address: from the first 10:08:0x to the next 10:08:1x (inclusive)
sed -n '/10:08:0/,/10:08:1/=' data/access.log | tr '\n' ' '

# 5) nested block: only inside the top-level environments: section, take keys indented two spaces (environment names)
sed -n '/^environments:/,/^[a-z]/{/^  [a-z]*:$/p;}' data/config.yaml
200 /healthz
200 /api/orders
200 /static/app.js
301 /
147 148 149 150 151 152 153 154 155
  dev:
  staging:
  prod:

In command 3, the .*" ([0-9]{3}) of .* is greedy that: it tries to extend as far right as possible, matching up to the last " three-digit number . In this log there is no such structure after the User-Agent, so the result is correct; if the UA happened to contain one, " 200 , the result would be wrong — which is exactly why “field-based processing should use awk”. Command 5 in } is prefixed with ; for BSD sed compatibility; the range's end address /^[a-z]/ is the next top-level key health:.

In-place editing: GNU vs BSD differences

cp data/config.yaml /tmp/c.yaml
# Portable form (works on GNU and BSD/macOS): suffix attached to -i, delete the backup afterwards
sed -i.bak -E 's/^(  log_level:[[:space:]]*)[a-z]+/\1debug/' /tmp/c.yaml && rm /tmp/c.yaml.bak
grep -n log_level /tmp/c.yaml          # only replace the value, keep end-of-line comments

# GNU only:               sed -i 's/…/…/' file
# BSD/macOS only:         sed -i '' 's/…/…/' file
# Most portable (any POSIX sed): write a temp file, then mv, preserving permissions
tmp=$(mktemp "${f}.XXXXXX") && sed 's/a/b/' -- "$f" > "$tmp" && chmod --reference="$f" "$tmp" 2>/dev/null; mv -- "$tmp" "$f"
4:  log_level: debug            # debug | info | warn | error
Portable syntax for a / i / c GNU allows sed '2i inserted'; POSIX/BSD require a backslash followed by a newline:
printf 'a\nb\nc\n' | sed '2i\
inserted'
a
inserted
b
c
# Common one-liners
sed -E 's/[[:space:]]+$//' file           # strip trailing whitespace
sed '/^[[:space:]]*#/d; /^[[:space:]]*$/d' app.conf   # strip comments and blank lines
sed 's/\r$//' win.txt                       # CRLF → LF
sed 's|/usr/local|/opt|g' paths.txt         # change the delimiter to avoid escaping /
sed -n '100,200p' big.log                   # extract a line range
sed '20q' big.log                           # equivalent to head -20: quits after reading line 20
sed --debug -n '/" 503 /p' data/access.log  # GNU: print how each command acts on the pattern space
How to verify / common errors / production uses Verify: run first without -i , and use diff <(sed … f) f to preview changes. Common errors: replacement text contains / or & variables (s/x/$url/) — escape them or change the delimiter first; inside double quotes, $ is expanded by the shell. Production use: rendering templates from environment variables in container startup scripts (preferred: envsubst), bulk-updating the base image tag in Dockerfiles.

Lab 2: log redaction and safe config editing

Goals: produce redacted logs that can be shared with external vendors; safely edit config and keep a backup. Environment: data generated by make-data.sh. Cleanup:rm -f /tmp/access.redacted.log /tmp/c.yaml*.

redact the last two octets of client IPs and the URL in the UA
cd ~/bashlab
sed -E -e 's/^([0-9]+\.[0-9]+)\.[0-9]+\.[0-9]+/\1.x.x/' \
       -e 's#https?://[^ ;)"]+#https://redacted#g' \
       data/access.log > /tmp/access.redacted.log
sed -n '307p' /tmp/access.redacted.log
192.0.x.x - - [17/Nov/2026:10:15:19 +0000] "GET / HTTP/1.1" 200 4120 "-" "O'Reilly-Bot/2.0 (it's \x22quoted\x22; +https://redacted)"
check for leftover full IPs — and false positives of the “verification rule” itself
grep -cE '([0-9]{1,3}\.){3}[0-9]{1,3}' /tmp/access.redacted.log
grep -oE '([0-9]{1,3}\.){3}[0-9]{1,3}' /tmp/access.redacted.log | sort | uniq -c
grep -cE '^([0-9]{1,3}\.){3}[0-9]{1,3} ' /tmp/access.redacted.log    # check column 1 only
83
     83 142.0.0.0
0

The 83 “leftover” lines are actually the URLs in the UA Chrome/142.0.0.0: the verification regex also needs context. Changed to check only the client IP at the start of the line; the result is 0.

Preview config changes (without -i)
cp data/config.yaml /tmp/c.yaml
diff -u /tmp/c.yaml <(sed -E 's/^(  log_level:[[:space:]]*)[a-z]+/\1debug/' /tmp/c.yaml)
@@ -1,7 +1,7 @@
 # opsctl sample config (Bash 8-hour course; read by the opsctl and yq examples from Lesson 3 onward)
 opsctl:
   version: "0.1"
-  log_level: info            # debug | info | warn | error
+  log_level: debug            # debug | info | warn | error

If written as s/^( log_level:).*/\1 debug/,.* it would eat the end-of-line comments too — a diff preview catches this.

Portable in-place edit and verifying the inode change
ls -i /tmp/c.yaml
sed -i.bak -E 's/^(  log_level:[[:space:]]*)[a-z]+/\1debug/' /tmp/c.yaml
ls -i /tmp/c.yaml /tmp/c.yaml.bak     # c.yaml is the new inode; .bak keeps the old inode
1310722 /tmp/c.yaml
1310730 /tmp/c.yaml  1310722 /tmp/c.yaml.bak
Think: if the log_level also appears at another nesting level,^ log_level: indentation anchoring will break. To really edit YAML, use the yq -i.

Case 1: sed -i broke tail -f and log rotation

Problem: Ops ran sed -i '/password=/d' app.log to delete a leaked password line; afterwards the monitoring agent (tail -f style) could no longer read new log lines. Cause:-i The edit creates a new inode, but the application keeps writing to the old inode (the unlinked file), while the agent follows the file name. Approach: Do not use sed -i; first fix the leak source, then process the rotated archive, or copytruncate use a write-to-a-new-file style. Limitation: Any tool that “replaces the file” has this problem, including editor save operations.

Case 2: CI script fails on a macOS dev machine

Symptom:sed: 1: "config.yaml": invalid command code c. Cause: BSD sed treats -i the script that follows as the backup suffix, and the file name as the script. Approach: Always use sed -i.bak … && rm *.bak, or on macOS brew install gnu-sed use gsed.

Case 3: bulk version bump

new=1.4.2
grep -rl --include='Dockerfile*' 'FROM myapp-base:' . | while IFS= read -r f; do
  sed -i.bak -E "s/^(FROM myapp-base:)[0-9.]+/\1${new}/" "$f" && rm -- "$f.bak"
done
git diff --stat

Limitation: When a variable is inserted into a double-quoted script,$new the /,&,\ characters break the expression; only write it this way when the version number is controlled input.

sed: -e expression #1, char 12: unknown option to `s'

Cause: the replacement text contains the delimiter /, common with values such as s/old/$path/. Diagnosis:printf '%s\n' "s/old/$path/" Check the expanded script. Fix: Switch to a different delimiter s|old|$path|, or escape it first: esc=$(printf '%s' "$path" | sed 's/[\/&]/\\&/g').

sed: 1: "file.txt": invalid command code f (macOS)

Cause: BSD sed's -i requires a suffix argument. Fix:sed -i.bak '…' file.txt (works on both) or sed -i '' '…' file.txt (BSD only).

sed: -e expression #1, char 9: invalid reference \1 on `s' command's RHS

Cause: In BRE, you wrote (…) but not -E, so there is no group; or there are too few groups. Fix: Add -E, or in BRE write \(…\).

sed: couldn't open temporary file ./sedAbC123: Permission denied

Cause:-i It needs to create a temp file in the directory that contains the file; that directory is not writable (even if the file itself is writable). Diagnosis:ls -ld "$(dirname f)". Fix: run as a user with permission; or sed … f > /tmp/x && cat /tmp/x > f (keeps the inode and permissions, but is not atomic).

Chinese text turns into garbage after replacement / [a-z] does not match the expected characters

Cause: the locale does not match the file encoding; LC_ALL=C under it, multibyte characters are processed byte by byte. Fix: For UTF-8 text, use LC_ALL=C.UTF-8; when only ASCII structures (IPs, status codes) are processed, use LC_ALL=C.

Command questions

1. Print the line numbers of all lines in access.log from the first 401 through the first 404, inclusive.
sed -n '/" 401 /,/" 404 /{=;/" 404 /q;}' data/access.log | tr '\n' ' '
# Actual output: 151 152 … 168 (lines 151–156 are six 401s; line 168 is the first 404)
# Without q: after the range ends, a later 401 starts a new range, so it may print all the way to the end of the file
2. Change the header of servers.csv to uppercase; leave the other lines unchanged (works on both GNU and BSD).
sed '1y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/' data/servers.csv | head -2
# NAME,ENV,REGION,IP,ROLE
# web-01,dev,canadacentral,10.10.1.21,web
# GNU-only, shorter: sed '1s/.*/\U&/'

Scenario analysis

A deploy script uses sed -i "s/^DB_PASS=.*/DB_PASS=$DB_PASS/" /etc/myapp/myapp.env to write a password. One day the password contained & and /, the deployment failed and the env file was corrupted. Analyze this and give a better approach.

① / ended the s command,& In the replacement part, & means “the whole match”, causing a syntax error or wrong content. ② The password appears in sed's command-line arguments, where it can be ps seen by others. ③ Better approach: don't build secrets with sed; use a template + envsubst, or read it from an environment variable with awk (awk -v also interprets backslashes, so use ENVIRON["DB_PASS"]), or a configuration tool (Ansible 's lineinfile + no_log). When writing, first write a temp file,chmod 600, then mv.

Verified instructional videos

▶
Linux Crash Course - The sed Command — Learn Linux TV
English · systematic walkthrough of s substitution, deletion and in-place editing; watch alongside this module's execution-cycle model

Official docs

Video storyboard script (about 75 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided for a video tool to produce.

Shot 1 · 0–20s
Visual: a conveyor belt feeds log lines one by one into a transparent box called the “pattern space”.
Narration: sed takes one line at a time, puts it in the pattern space, then runs the script from the top.
Shot 2 · 20–45s
Visual: on a healthz line, the d command empties the box and the belt brings the next line straight in; other lines have their IP rewritten by the s command.
Narration: d ends the current cycle immediately, so the commands after it do not run; lines that are not deleted are printed automatically when the script ends.
Shot 3 · 45–75s
Visual: -i Action: a temp file appears next to the old file; finally the temp file, as a stand-in, takes the original name, and the old inode greys out.
Narration: in-place editing actually writes a new file and then renames it. GNU and macOS use different syntax; -i.bak works on both.
or score ≥ 70% on the quiz

Module 3 · awk: fields, patterns and aggregate reports

13:00 – 21:00 · Record → field → pattern → action → END summary: a small language designed for “processing text by column”
8 minPOSIX awk · gawk 5.3.2 / mawk 1.3.4★★★★★
Learning objectives
  • Explain awk's execution model: BEGIN → each record (RS split) → field splitting (FS) → each rule in turn pattern { action } → END; you will use NR NF FNR FILENAME $0 $NF.
  • Use associative arrays for counting, summing and de-duplication, and use printf produce aligned report output; know that for (k in a) 's order is undefined, so you need to sort.
  • Set FS/OFS (and $1=$1 rebuilding records), use -v / ENVIRON to pass values; write POSIX awk that runs on both gawk and mawk.
Prerequisites: Module 1's ERE (awk's regex is ERE). Importance:★★★★★ (Module 8's opsctl reports are based entirely on this module)

What: awk is a language

awk (Aho, Weinberger, Kernighan, 1977) treats input as a stream of records (by default, one line) and fields (by default, split on runs of whitespace). A program consists of several pattern { action } rules: for each record, each pattern is tested from top to bottom, and if true its action runs. Omitting the pattern means “run for every record”; omitting the action means { print $0 } (so awk 'NR<=3' is the same as head -3,awk 1 is the same as cat).

Why: why use awk for reports

  • Test by column: $9 >= 500 is a numeric comparison, so it will not falsely match byte counts or times — grep/sed cannot do this.
  • Single-pass aggregation: associative arrays count[$7]++ one pass gives grouped counts, with no need for sort | uniq -c the sorting overhead of a pipeline (a clear difference on GB-scale logs).
  • Available everywhere: a POSIX-standard tool; every Linux, macOS and BusyBox container has an awk.

How: built-in variables and execution order

VariableMeaningDefault / notes
$0,$1…$NFwhole record, nth field, last fieldAssigning to $n triggers a rebuild of OFS $0 using OFS $0
NR / FNRGlobal record number / record number in the current fileNR==FNR is the idiom for “reading the first file”
NFNumber of fields in the current recordassignable,NF-- deletes the last field (gawk/mawk support)
FS / OFSInput / output field separatorFS default " ": special value meaning “skip leading and trailing whitespace, split on runs of whitespace”; a single other character is split literally; multiple characters are split as ERE
RS / ORSInput / output record separatordefault is newline; RS="" setting it to empty gives paragraph mode
FILENAME,ENVIRON,ARGVcurrent file name, ENVIRON array, argument arrayENVIRON["HOME"]
  1. Process -v -v assignments, run all BEGIN BEGIN blocks (no input has been read yet).
  2. Per RS read one record into $0,NR++ FNR++, and split by FS into $1..$NF (gawk/mawk split lazily, but the semantics are the same).
  3. test each pattern in turn; next next immediately jumps to the next record,exit exit jumps to END.
  4. After input ends, run END: at this point $0/NF $0 still holds the last record (POSIX allows this),NR NR is the total record count.

When: gawk or mawk?

FeaturePOSIX awkgawk 5.3mawk 1.3.4
Associative arrays, printf, split, sub/gsub, match, tolower✓✓✓
length(arr)Not defined in older POSIX (all major implementations support it)✓✓
{n,m} Interval expressions✓✓Supported by default in newer versions (older mawk does not support it; avoid relying on it)
gensub,asort/asorti,PROCINFO["sorted_in"]✗✓✗
FPAT,--csv (new in 5.3)✗✓✗
strftime/systime/mktime✗✓✓ (newer versions)
match(s, re, arr) Third argument✗✓✗
Speedmawk is usually faster and uses less memory; gawk has the most features and the best error messages (--lint,--posix)

On Ubuntu, the awk is an alternatives link: a minimal install usually has only mawk; server and cloud images often pull in gawk as a dependency, and gawk's higher priority makes it take over awk. Use readlink -f /etc/alternatives/awk to confirm. Script principle: if you use only POSIX features, write awk; if you use gawk features, explicitly write gawk and check for it util::require_cmd gawk.

Common misconceptions① “for (k in a) in insertion order” — the order is undefined; it can differ across implementations and data sizes, so reports must be sorted again (| "sort" or an external sort). ② “-F' ' and -F'[ ]' are the same”: the former is the special value “runs of whitespace”; the latter treats every space as a separator, so consecutive spaces produce empty fields. ③ “awk -v pass="$P" passes values through as-is”——-v processes backslash escapes,a\tb turns it into a tab; to pass values literally, use ENVIRON["P"].
BEGIN { }After -v assignments Input streamfiles… or stdin Split records by RS$0, NR++, FNR++ Split fields by FS$1 … $NF, NF Run rules in orderpattern1 { action1 }pattern2 { action2 }next → next record; exit → END END { summary, printf }NR = total record count Next record (loop) EOF
Figure 3-1 awk execution model: BEGIN → loop (record → fields → rules) → END
FS default " ": split on runs of whitespace — quotes are not separators! 198.51.100.23 [17/Nov/2026:10:08:06 +0000] "POST /login HTTP/1.1" 401 64 "-" "python-…" $1 IP$2 $3$4 time$5$6 method$7 path$8$9 status$10$11$12…$NF ✓ $1–$11 positions are stable (IP, time, method, path, protocol, status, bytes, Referer contain no spaces) ✗ User-Agent may contain spaces, single quotes, \x22 (line 307): NF is 12/15/21/24 and varies, so $12 cannot be used as the UA When you need the UA: use gawk's FPAT / match(), or have the application emit JSON logs and process them with jq (Module 6)
Figure 3-2: fields that the default FS produces from line 151 (one 401 in a brute-force attempt): the first 11 are reliable, the UA is not

Core animation: awk processes access.log record by record

with this program (a stripped-down version of the same idea as the Module 8 reports). Each step corresponds to one real action inside the awk interpreter: read a record (RS) → split fields (FS) → test patterns → run actions that update the associative arrays → run END after reading everything. The array table on the right is the contents of awk's hash tables.

$9 !~ /^[1-5][0-9][0-9]$/ { bad++; next }      # Rule 1: invalid status code → skip
{ hits[$7]++; status[$9]++; bytes += $10        # Rule 2: runs for every valid record
  if ($9 >= 500) e5++ }
END { for (k in hits) printf "%4d %s\n", hits[k], k | "sort -rn"
      close("sort -rn"); printf "5xx: %.1f%%\n", 100*e5/(NR-bad) }
$0 = (not read yet)
hits[$7]
keyvalue
status[$9] · scalar
keyvalue
Ready: take 8 lines from access.log, plus 1 corrupted record.
$ awk -f report.awk data/access.log

Syntax overview

FormPurposeExample
awk 'pattern {action}' fileBasic formawk '$9>=500' f
-F sep / -v var=val / -f prog.awkInput separator / pass variables / program fileawk -F, -v env=prod '$2==env'
/re/,$7 ~ /re/,!~Regex match on whole line / on a field$7 ~ /^\/api\//
p1, p2Range pattern/START/,/END/
a[k]++,k in a,delete a[k]Associative array counting, existence test, deletion!seen[$1]++ (de-duplicate, keeping order)
printf fmt, …Formatted output%-15s %6d %5.1f%%
split(s, arr, sep),substr(s, i, n),index,lengthString handling (indexes start at 1)split($4, t, ":")
sub(re, rep[, t]),gsub,match,tolowerSubstitution and matchingsub(/\?.*/, "", p)
print … | "cmd",close("cmd"),print > "/dev/stderr"Output to a pipe / close a pipe / write to stderr| "sort -rn"
next,exit [code],getlineSkip, exit (END still runs), read a line manuallyexit 1
cd ~/bashlab && export LC_ALL=C
awk 'NR==2 {print NF; print $1, $7, $9, $10; print $NF}' data/access.log
awk '$9 >= 500 {print NR": "$1, $7, $9}' data/access.log | head -4
21
192.0.2.10 /api/orders 200 4262
Safari/537.36"
43: 192.0.2.12 /api/orders 503
130: 192.0.2.11 /api/orders 500
136: 10.20.1.31 /api/orders 503
185: 10.10.1.22 /api/orders 503

Line 2 has NF=21: the Chrome UA was split into 10 fields. The field-count distribution across the file is 12 (422 lines), 15 (1 line), 21 (83 lines), 24 (105 lines) — only the first 11 field positions are stable.

# Per IP: request count, total bytes, average bytes; top 5 by total bytes, descending
awk '{ b[$1] += $10; n[$1]++ }
     END { for (ip in b) printf "%-15s %3d req %8d bytes %8.1f avg\n", ip, n[ip], b[ip], b[ip]/n[ip] }' \
    data/access.log | sort -k4,4nr | head -5
10.10.1.22       64 req   412956 bytes   6452.4 avg
192.0.2.11       54 req   352316 bytes   6524.4 avg
203.0.113.7      64 req   331804 bytes   5184.4 avg
10.10.1.21       58 req   277887 bytes   4791.2 avg
192.0.2.10       61 req   268469 bytes   4401.1 avg
# Requests bucketed by 10 minutes: $4 = "[17/Nov/2026:10:00:01"; the time starts at character 14
awk '{ c[substr($4, 14, 4) "x"]++ } END { for (k in c) print k, c[k] }' data/access.log | sort

# De-duplicate, keeping order (print on first occurrence)
awk '!seen[$1]++ { print $1 }' data/access.log | head -4
10:0x 195
10:1x 213
10:2x 185
10:3x 18
203.0.113.7
192.0.2.10
172.16.5.4
10.10.1.22

10:3x has only 18 lines: the log ends at 10:31:00, which is not a traffic drop — when bucketing, check whether the window is complete.

# FS / OFS: $1=$1 forces the record to be rebuilt with OFS
awk -F, -v OFS='\t' 'NR>1 { print $1, $4 }' data/servers.csv | head -2
awk -F, -v OFS=' | ' '{ $1 = $1 } 1' data/servers.csv | head -2
awk -F, 'BEGIN { OFS = "," } { $2 = toupper($2) } 1' data/servers.csv | head -2
web-01	10.10.1.21
api-01	10.10.1.22
name | env | region | ip | role
web-01 | dev | canadacentral | 10.10.1.21 | web
name,ENV,region,ip,role
web-01,DEV,canadacentral,10.10.1.21,web
# Passing values: -v interprets escapes; ENVIRON is literal; for numeric comparisons make sure the value is a number ($10 may be "-")
awk -v th=40000 '$10+0 > th { print $1, $10 }' data/access.log | sort | uniq -c | sort -k1,1nr | head -3
TOKEN='a\tb' awk 'BEGIN { print ENVIRON["TOKEN"] }'     # prints a\tb unchanged
awk -v t='a\tb' 'BEGIN { print t }'                     # prints a<TAB>b

# Join two files (NR==FNR reads the first file to build a table): add “host@env” to the IPs in the access log
awk -F'[ ,]' 'NR==FNR { name[$4] = $1 "@" $2; next } { print $1, ($1 in name ? name[$1] : "-") }' \
    data/servers.csv data/access.log | sort | uniq -c | sort -k1,1nr -k2 | grep -v ' -$'   # only show the matched ones


# printf format
awk 'BEGIN { printf "%5.1f%%|%-8s|%08.3f\n", 15, "ab", 3.14159 }'
      7 10.10.1.22 48213
      6 192.0.2.11 48213
      5 203.0.113.7 48213
a\tb
a	b
     64 10.10.1.22 api-01@dev
     58 10.10.1.21 web-01@dev
     51 10.20.1.31 web-01@staging
 15.0%|ab      |0003.142

Of the 11 client IPs, 3 are internal servers from the inventory (web-01 and api-01 in dev, and web-01 in staging); the rest are external clients. Note that host names in servers.csv repeat across environments (web-01 has three hosts), so the join key is the IP and the environment is shown in the output. On line 11, the "web,api" makes -F'[ ,]' split into 6 fields, but $4 (the IP) is still in field 4 and is unaffected — joining on column 5 would go wrong (Module 7).

How to verify / common errors / production use Verification: when developing an awk program, first NR<=5 { print NF": "$0 } check that the splitting matches expectations; gawk can use --lint to check it. Common errors: wrapping the program in double quotes causes $1 to be expanded by the shell (single quotes are required); confusing numeric and string comparisons ($9 == "500" and $9 == 500 in 500.0 differ). Production use: instant analysis of Nginx/ALB logs,df/ps threshold alerts on the output,kubectl get pods filtering of columns.

Lab 3: write a reusable awk program file

Goal: Turn a one-line awk command into a commented program file that runs on both gawk and mawk. Environment: data generated by make-data.sh; optional sudo apt-get install -y mawk gawk. Cleanup:rm -f /tmp/status.awk.

Write the program file
cat > /tmp/status.awk <<'EOF'
# Count by status code; POSIX awk
$9 ~ /^[1-5][0-9][0-9]$/ {
  total++
  cls = substr($9, 1, 1) "xx"
  n[cls]++
}
END {
  for (c in n) printf "%-4s %4d %6.1f%%\n", c, n[c], 100 * n[c] / total | "sort"
  close("sort")
  printf "total %4d\n", total
}
EOF
awk -f /tmp/status.awk ~/bashlab/data/access.log
2xx   504   82.5%
3xx    53    8.7%
4xx    26    4.3%
5xx    28    4.6%
total  611
Compare on both implementations
for a in mawk gawk 'gawk --posix'; do
  command -v ${a%% *} >/dev/null || continue
  echo "== $a"; $a -f /tmp/status.awk ~/bashlab/data/access.log | tail -1
done
== mawk
total  611
== gawk
total  611
== gawk --posix
total  611
Add a parameter: count only a given path prefix
awk -v prefix=/api/ 'index($7, prefix) == 1' ~/bashlab/data/access.log | awk -f /tmp/status.awk
2xx   230   82.7%
4xx    20    7.2%
5xx    28   10.1%
total  278

Use index() instead of $7 ~ prefix: the prefix is a literal string and should not be interpreted as a regex.

Observe that for-in order is undefined: remove | "sort" and run it several times, switching between mawk and gawk, to observe the order. Conclusion: always sort report output explicitly.

Case 1: “live SQL” on ALB / Nginx logs

Problem: After a release, a 5xx alert fired; within one minute we need to know “which path, which upstream, and since when”. Approach:awk '$9>=500 { c[substr($4,14,5)" "$7]++ } END { for (k in c) print c[k], k }' access.log | sort -k2 Get the error distribution of “per minute × path”. Limitation: Only suitable for a single host or logs already pulled to one place; leave long-term analysis to the log platform.

Case 2: gensub error on mawk makes a cron job fail

Symptom: The same script works on the developer's laptop (gawk) but reports an error on a newly built minimal Ubuntu image: function gensub never defined. Approach: Switch to POSIX sub/gsub + temporary variables; or check at the top of the script and explicitly call gawk. Limitation: FPAT,--csv,asort etc. are also gawk-only.

Case 3: df disk threshold alert

df -P -x tmpfs -x devtmpfs | awk -v max=85 'NR>1 { u = $5; sub(/%/, "", u); if (u+0 > max) { printf "%s %s%%\n", $6, u; bad = 1 } } END { exit bad }'

Key points:-P Keep POSIX output format (long device names must not wrap); exit bad let the script if ! …; then alert; fi.

awk: line 1: function gensub never defined

Cause: mawk (or BusyBox awk) does not have gawk's extension functions. Diagnosis:readlink -f "$(command -v awk)". Fix: Rewrite it in POSIX (s = $0; sub(/re/, "x", s)), or install and explicitly call gawk.

awk: cmd. line:1: ^ syntax error (the $1 in the program disappeared)

Cause: The program was wrapped in double quotes, so the shell first expands $1,$NF to empty strings. Diagnosis:set -x Check the program actually passed to awk. Fix: Always single-quote the program and pass variables in with -v .

Wrong report numbers: fields are “shifted”

Cause: Some lines have a different number of fields (for example, a request line like "-", a path with an unencoded space, or the UA first), or the CSV contains quoted commas. Diagnosis:awk '{print NF}' f | sort | uniq -c Check the distribution of field counts. Fix: Add a validation pattern ($9 ~ /^[0-9]{3}$/), count the abnormal lines and skip them; for CSV, use the method from Module 7.

awk: division by zero

Cause: The input is empty or everything was filtered out, so in END x/total total is 0. Fix:if (total == 0) { print "no data" > "/dev/stderr"; exit 1 } (the approach from Module 8).

awk is very slow / memory spikes on large files

Cause: character handling under a UTF-8 locale; or the associative array's keys have too high cardinality (for example, counting by full URLs including query strings). Fix:LC_ALL=C; normalize keys first (strip the query string, replace IDs with :id); mawk is usually faster than gawk.

Command questions

1. For each path (with the query string removed), output its request count and 4xx count, in the format “path request-count 4xx-count”, sorted by request count in descending order.
awk '{ p = $7; sub(/\?.*/, "", p); n[p]++; if ($9 ~ /^4/) e[p]++ }
     END { for (p in n) print p, n[p], e[p] + 0 }' data/access.log | sort -k2,2nr -k1,1
# /api/orders 211 11
# /healthz 121 0
# / 75 0
# /login 74 6
# /api/orders/1042 67 9
# /static/app.js 63 0
2. Print the host count and the list of hosts for the prod environment in servers.csv (one line, comma-separated), without using sort/paste. (Hint: line 11 has a quoted comma, but using only $1 and $2 is not affected.)
awk -F, 'NR>1 && $2=="prod" { list = list (n++ ? "," : "") $1 } END { print n": "list }' data/servers.csv
# 6: web-01,web-02,api-01,edge-01,db-01,bastion-01

Scenario analysis

You wrote awk '{print $12}' access.log | sort | uniq -c wanted to count User-Agent, but got many "Mozilla/5.0 and "bot. Why? Give two improvement options.

The default FS splits on whitespace, and the UA itself contains spaces,$12 so only the first word of the UA is captured. Option 1: use the double quote as the field separator awk -F'"' '{print $6}'— this fails for UAs with escaped quotes \" (such as the scanner in the sample) still break. Option 2: gawk match($0, /"[^"]*"$/) takes the last quoted string, or use a parser that handles escapes; Option 3 (best): have nginx output JSON-format logs (log_format … escape=json), and process them with jq.

Verified instructional videos

▶
Linux Crash Course - awk — Learn Linux TV
English · awk basics: fields, patterns, separators
▶
AWK Is Still Very Useful | Brian Kernighan and Lex Fridman — Lex Clips
English · interview clip · one of the awk authors on why it is still useful (design philosophy)
▶
How The 'awk' Command Made Me A 10x Engineer — RobertElderSoftware
English · hands-on, showing awk on real data

Official docs

Video storyboard script (about 90 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided for a video tool to produce.

Shot 1 · 0–20s
Visual: a line of the access log is cut into 14 pieces by a “whitespace knife”, labeled $1 to $NF in order; $7 and $9 glow.
Narration: awk reads a line and first splits it into fields by whitespace. The path is column 7; the status code is column 9.
Shot 2 · 20–50s
Visual: two hash tables, hits and status, appear on the right; each line read increments the matching cell by one.
Narration: associative arrays are the heart of awk. One pass completes the grouped counts, with no need to sort first.
Shot 3 · 50–70s
Visual: a corrupted record is stopped by rule one, the bad counter goes up by one, and the arrow jumps straight to the next line.
Narration: write the validation rule first, then the counting rules. next keeps bad data from polluting the results.
Shot 4 · 70–90s
Visual: in the END block, for-in spits out lines in random order; after a sort pipeline they become a neat ranking.
Narration: the traversal order of arrays is not guaranteed, so reports must be sorted.
or score ≥ 70% on the quiz

Module 4 · find, xargs and safe file name handling

21:00 – 28:00 · A file name can contain any byte except “/” and NUL — including spaces, newlines and leading dashes
7 minGNU findutils 4.10.0★★★★★
Learning objectives
  • Write find expressions (tests, actions, operators,-prune), and understand that they are evaluated left to right with short-circuiting.
  • Explain find | xargs why it is unsafe, and master three safe patterns: -print0 | xargs -0,-exec … {} +,while IFS= read -r -d ''.
  • Understand how xargs splits input into batches of argv (ARG_MAX,-n,-P,-r), and the meaning of exit codes 123/124/125/126/127; use -- and ./ to guard against leading dashes.
Prerequisites: Lesson 1's word splitting and globbing; Module 1's grep -Z. Importance:★★★★★ (file name bugs are the number one cause of bulk-deletion accidents)

What: what find and xargs each handle

find recursively walk the directory tree (openat + getdents64), evaluate the expression for each entry and run the action (default -print). xargs Read “items” from stdin and append them to the command's argument list and run the command; if there are too many arguments, split them into batches, one call per batch fork + execve.

Why: why you need xargs / -exec +

  • Argument length limit: rm data/*.log With many files it fails with “Argument list too long” (E2BIG): the kernel limits a single execve argument plus environment total length (getconf ARG_MAX, Linux usually 2 MiB; the practical limit is about 1/4 of the stack limit).
  • Process overhead: -exec cmd {} \; one process is started per file; {} + or xargs merges hundreds or thousands of files into a single call.
  • Concurrency: xargs -P 4 run 4 processes at once (compression, upload, verification).

How: comparison of three delimiter methods

FormSplitting rulesSpaceQuotes / backslashesNewlineAssessment
find … | xargs cmdWhitespace and newlines; quotes and backslashes have special meaning✗ Split apart✗ Reports “unmatched single quote”✗ Split apartDo not use
find … | xargs -d '\n' cmd (GNU)Split on newlines only✓✓✗Acceptable (when file names contain no newlines)
find … -print0 | xargs -0 cmdSplit on NUL only✓✓✓Recommended (POSIX 2024 standardized -print0 and xargs -0)
find … -exec cmd {} +Does not go through text; builds argv directly✓✓✓Recommended (POSIX, simplest)
while IFS= read -r -d '' f; do …; done < <(find … -print0)Bash reads by NUL✓✓✓when you need per-file logic

When: which one to choose

  • Run the same command on a batch of files: find … -exec cmd -- {} +.
  • For parallelism, or when input comes from grep -lZ / git ls-files -z or other NUL-delimited output: xargs -0 -P N.
  • Each file needs several steps of Bash logic (rename, test, accumulate): while read -d '' loop (use process substitution to avoid losing variables in a pipeline subshell — Lesson 2 content).
  • Only in the current directory: just use a glob for f in ./*.log— the glob result is itself safe as arguments, with no word splitting.
Common misconceptions① “for f in $(find …) is fine” — command substitution results undergo word splitting and glob expansion, so spaces and asterisks cause trouble. ② “-exec rm {} + is already safe” — if a file name starts with - and find's starting point is ., the path will be ./-rf.txt, which is safe; but cd dir && rm * in -rf.txt will be treated as an option; write rm -- * or rm ./*. ③ “-delete and -exec rm are the same”—-delete implies -depth, and placing it at the very front of an expression deletes all files (expressions are evaluated left to right).
findgetdents64 traversal-type f -print0 pipe buffer (64 KiB)a.log␀report 2026.txt␀… xargs -0split by ␀accumulate up to the argv limit fork+execve batch 1 fork+execve batch 2 Exit codes (GNU xargs) 0 all succeeded · 123 a command invocation exited with 1–125 · 124 a command invocation exited with 255 (xargs stops immediately) 125 command killed by a signal · 126 command cannot be executed · 127 command not found · 1 other error (such as an unmatched quote in the input)
Figure 4-1 find -print0 | xargs -0: NUL is the only byte that can never appear in a file name, so it is the only safe separator
-exec cmd {} \; cmd ./a.logcmd ./b.logcmd ./c.log … one process per file Pros: {} can go anywhere; each file's exit code affects find's true/false resultCons: slow (100,000 files = 100,000 fork/exec calls) -exec cmd {} + cmd ./a.log ./b.log ./c.log … (up to ARG_MAX) Pros: few processes, no text separation, POSIXLimit: {} must be the last argument before +any batch failing → find's final exit code is non-zero When the files need to go in the middle: sh -c 'cp -- "$@" /dst' sh {} +
Figure 4-2 \; and +: one call per file vs one call for the whole batch

Core animation: find -print0 | xargs -0 data flow in

The input is data/files/ 6 of 15 files (two spaces, a leading dash, a space, a single quote, a newline, a double quote). Switch modes and step through to observe: the byte stream find writes into the pipe byte stream (⏎ = newline, ␀ = NUL) → xargs' split result → batched as “at most 3 arguments per batch” (for demo -n 3; the real limit is set by ARG_MAX) to form argv → execve.

① find → byte stream in the pipe
② arguments split out by xargs
③ batching and execve(argv)
Ready.
$ strace -f -e trace=getdents64,write,read,execve … (illustrative)

find expression overview

CategoryFormDescription
Tests-type f|d|l -name '*.log' -iname -path -size +10M -mtime +7 -mmin -30 -newer f -user -perm -o+w -emptyPatterns must be quoted, otherwise the shell expands the glob first; -mtime +7 means “more than 7×24 hours” (truncated to whole days)
Actions-print -print0 -printf (GNU) -exec … \; -exec … + -execdir -ok -delete -quitWhen there is an explicit action, the default -print
Operators! -a (default) -o \( … \)-o has lower precedence than the implicit -a, so use parentheses when mixing
Positional options-maxdepth N -mindepth N -xdev -depthGNU requires them before tests; -xdev do not cross file systems
Pruning-path ./.git -prune -o -type f -printdo not descend into .git; remember to add an explicit -print
cd ~/bashlab/data && export LC_ALL=C
# ✗ Dangerous: split on newlines and whitespace; quotes have special meaning
find files -type f | xargs printf '[%s]\n'
xargs: unmatched single quote; by default quotes are special to xargs unless you use the -0 option
[files/--verbose.log]
[files/-n]
[files/.hidden.txt]
[files/café-ünïcode.txt]

Upon reading it's.txt a single quote, xargs errors out and exits: only the 4 files before it are processed; the 11 after it are not — if the command was rm, you end up with a “half-done” state. Even without quotes,two spaces.txt,report 2026.txt is also split into two arguments,line1⏎line2.txt becoming two nonexistent paths.

# ✓ Safe 1: -print0 | xargs -0
find files -type f -print0 | xargs -0 printf '[%s]\n'

# ✓ Safe 2: -exec … {} +   (one call receives all files)
find files -type f -exec sh -c 'echo "argc=$#"' sh {} +

# Batching: -n limits the number of arguments per batch
find files -type f -print0 | xargs -0 -n 5 sh -c 'echo "argc=$#"' sh
[files/--verbose.log]
[files/-n]
[files/.hidden.txt]
[files/café-ünïcode.txt]
[files/it's.txt]
[files/line1
line2.txt]
[files/price $5.txt]
[files/report 2026.txt]
[files/say "hi".txt]
[files/star*.txt]
[files/sub dir/nested file.log]
[files/tab	here.txt]
[files/trailing-space.txt ]
[files/two  spaces.txt]
[files/[draft] notes.md]
argc=15
argc=5
argc=5
argc=5
# ✓ Safe 3: process one at a time, using %q to show “invisible” characters
while IFS= read -r -d '' f; do
  printf '%q\n' "$f"
done < <(find files -type f -print0 | sort -z)

# Count files correctly: output one dot per file, then count bytes
find files -type f | wc -l                 # 16 ✗ (a file name with a newline is counted as 2 lines)
find files -type f -printf . | wc -c       # 15 ✓ (GNU)
find files -type f -exec printf . \; | wc -c   # 15 ✓ (POSIX)
files/--verbose.log
files/-n
files/.hidden.txt
files/\[draft\]\ notes.md
files/café-ünïcode.txt
files/it\'s.txt
$'files/line1\nline2.txt'
files/price\ \$5.txt
files/report\ 2026.txt
files/say\ \"hi\".txt
files/star\*.txt
files/sub\ dir/nested\ file.log
$'files/tab\there.txt'
files/trailing-space.txt\
files/two\ \ spaces.txt
16
15
15
# Leading dashes: -- and ./
cd files
ls -l -- -n               # everything after -- is an operand (otherwise -n is the “numeric uid/gid” option)
ls -l ./--verbose.log      # or add a ./ prefix
for f in ./*; do printf '%s\n' "$f"; done | head -3   # use ./* instead of * for the glob
cd ..

# Empty input: GNU xargs still runs the command once by default; -r (--no-run-if-empty) avoids it
printf '' | xargs echo run         # prints run
printf '' | xargs -r echo run      # no output (BSD xargs does not run by default)

# Concurrency: 4 gzip processes at once, 16 files per batch; xargs returns 123 on failure
find logs -name '*.log' -mtime +1 -print0 | xargs -0 -r -P 4 -n 16 gzip -9 --
echo "rc=$?"

# Dry run first: use -print / echo, then switch to the real action once confirmed
find files -name '*.tmp' -mtime +7 -print
find files -name '*.tmp' -mtime +7 -exec echo rm -- {} +
find files -name '*.tmp' -mtime +7 -delete       # put -delete last!
How to verify / common errors / production use Verification: replace the action with printf '%q\n' to see each argument clearly first; xargs -t (GNU) prints the command line to stderr before running; xargs --show-limits check the real argv limit. Common errors: -name *.log unquoted; find . -delete -name '*.tmp' (running delete before testing, deleting everything); xargs -I{} implies one argument per line split by newlines, losing batching. Production use: log cleanup and compression, bulk checksum computation, concurrent uploads to object storage.

Lab 4: bulk operations on weird file names

Goal: On data/files/ the 15 weird file names, do bulk renaming, bulk size calculation and bulk deletion, without damaging any file name. Environment: Data generated by make-data.sh. Risk: Only inside ~/bashlab/data/files operate. Cleanup:bash ~/bashlab/make-data.sh Rebuild to restore.

Observe what the dangerous forms do (read-only)
cd ~/bashlab/data
find files -type f | xargs -n1 echo "would touch:" 2>&1 | head

Compare: count whether the number of output lines matches the actual number of files.

Safely prefix all .txt files with bak_ (each file needs a computed new name → while loop)
while IFS= read -r -d '' f; do
  dir=${f%/*} base=${f##*/}
  mv -n -- "$f" "$dir/bak_$base"
done < <(find files -type f -name '*.txt' -print0)
ls -b files
--verbose.log
-n
[draft]\ notes.md
bak_.hidden.txt
bak_café-ünïcode.txt
bak_it's.txt
bak_line1\nline2.txt
bak_price\ $5.txt
bak_report\ 2026.txt
bak_say\ "hi".txt
bak_star*.txt
bak_tab\there.txt
bak_two\ \ spaces.txt
sub\ dir
trailing-space.txt\ 

trailing-space.txt␠ not renamed: its name ends with a space, so it does not match *.txt— a glob is also an exact match.

Bulk size count (-exec +)
find files -type f -exec du -b -- {} + | awk '{s += $1} END {print NR, "files,", s, "bytes"}'
16 files, 126 bytes

NR is 16, not 15 —du because the output file name contains a newline. awk processes by line, so it counts one extra record; GNU du -0 (--null) can output with NUL terminators; combine with awk -v RS='\0' (supported by gawk/mawk) to fix it.

Process concurrently and check exit codes
find files -type f -print0 | xargs -0 -r -P 3 -n 2 grep -q -- 'no-such-text'
echo "rc=$?"
rc=123

Every grep invocation found nothing (exit code 1) → xargs reports 123. The script should check this rather than ignore it.

Delete files with spaces after a dry run
find files -type f -name '* *' -exec printf 'rm %q\n' {} +
find files -type f -name '* *' -exec rm -- {} +
ls -b files
rm 'files/bak_price $5.txt'
rm 'files/bak_report 2026.txt'
rm 'files/bak_say "hi".txt'
rm 'files/bak_two  spaces.txt'
rm 'files/sub dir/nested file.log'
rm 'files/trailing-space.txt '
rm 'files/[draft] notes.md'

Acceptance

Case 1: a cleanup script deleted the whole upload directory

Problem: A nightly job find /srv/uploads -mtime +30 | xargs rm -rf. A user had uploaded a file named tmp /srv/uploads … xargs split on spaces into /srv/uploads, so the whole directory was deleted. Approach:find /srv/uploads -xdev -type f -mtime +30 -delete (delete only files, do not cross file systems); when an external command is needed, use -exec rm -f -- {} +. Limitation: Before going live, use -print a dry run and record the count; combined with backups and object-storage lifecycle policies, it is safer.

Case 2: Argument list too long

Problem:gzip /var/log/app/*.log E2BIG was reported when 300,000 files had accumulated. Approach:find /var/log/app -maxdepth 1 -name '*.log' -print0 | xargs -0 -r -P "$(nproc)" -n 200 gzip --. Limitation: Concurrency competes for disk I/O; in production, control -P and use ionice -c3.

Case 3: bulk ShellCheck in a git repository

git ls-files -z -- '*.sh' 'bin/*' | xargs -0 -r shellcheck --

Key points:git ls-files -z,grep -lZ,find -print0,sort -z,du -0 can all output NUL-delimited lists; combined, the whole pipeline is safe (used in the Lesson 7 CI).

xargs: unmatched single quote; by default quotes are special to xargs unless you use the -0 option

Cause: In default mode, xargs interprets quotes, and the file name contains ' or ". Fix:find … -print0 | xargs -0; when the input comes from another command, use xargs -d '\n' (GNU).

bash: /usr/bin/rm: Argument list too long

Cause: The total length of the arguments after glob expansion exceeds the execve limit. Diagnosis:getconf ARG_MAX,xargs --show-limits </dev/null. Fix:find … -exec rm -- {} + or printf '%s\0' ./*.log | xargs -0 rm -- (printf is a builtin and is not subject to the execve limit).

find: paths must precede expression: `b.log'

Cause:-name *.log Unquoted, the current directory has several .log files, and the shell expands them into multiple arguments. Fix:-name '*.log'.

find: warning: you have specified the global option -maxdepth after the argument -type

Cause: GNU find's global options must come before the tests. Fix:find . -maxdepth 1 -type f.

rm: invalid option -- 'r' / ls: invalid option -- 'f'

Cause: The file name starts with - (-rf.txt) is treated as an option. Fix:rm -- "$f" or rm ./-rf.txt write the glob as ./*. ShellCheck SC2035 flags this issue.

The script exits with 123 but no error is visible

Cause: a command invoked by xargs exited with 1–125, and its error output was redirected or -P buried by concurrent output. Diagnosis:xargs -t Print each command being run; remove -P and rerun. Fix: Make the subcommand print error messages that include the file name, and handle non-zero exit codes in the script.

Command question

1. Find all .sh files under ~/bashlab that contain “TODO”, and count the TODO lines in each file; the solution must be safe for any file name.
grep -rlZ --include='*.sh' 'TODO' ~/bashlab | xargs -0 -r grep -c -- 'TODO'
2. Delete .log files under data/files that were modified more than 7 days ago and are not in the keep/ subdirectory (dry run first).
find data/files -path data/files/keep -prune -o -type f -name '*.log' -mtime +7 -print
find data/files -path data/files/keep -prune -o -type f -name '*.log' -mtime +7 -exec rm -- {} +

Scenario analysis

A backup script: for f in $(ls /data/*.csv); do aws s3 cp $f s3://bkt/; done. List all of its problems and rewrite it.

Problems: ① parsing ls output + unquoted command substitution → spaces, newlines and glob characters all break; ② $f unquoted; ③ no --; ④ one process per file, no concurrency, no exit-code handling; ⑤ when nothing matches, /data/*.csv the literal pattern is passed through. Rewrite:

shopt -s nullglob
files=(/data/*.csv)
((${#files[@]})) || { log::warn "no CSV"; exit 0; }
printf '%s\0' "${files[@]}" | xargs -0 -P 4 -I{} aws s3 cp -- {} s3://bkt/ || util::die "upload failed" 1
# or directly: aws s3 sync /data s3://bkt/ --exclude '*' --include '*.csv'

Verified instructional videos

▶
Lecture 4: Data Wrangling (2020) — Missing Semester
English · MIT “The Missing Semester of Your CS Education”, covering combined use of grep/sed/awk/sort/uniq/xargs
▶
The 50 Most Popular Linux & Terminal Commands - Full Course for Beginners — freeCodeCamp.org
English · long video · you can jump by chapter to the find / xargs part

No dedicated, verified video was found covering -print0 | xargs -0 safe patterns; rely on the animations in this module and the docs below.

Official docs

Video storyboard script (about 90 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided for a video tool to produce.

Shot 1 · 0–20s
Visual: a row of file cards; one has a newline in its name, one starts with a dash, one has a single quote.
Narration: a file name can contain any character except slash and the null byte.
Shot 2 · 20–45s
Visual: in an ordinary pipe, newlines and spaces cut file names like scissors; xargs hits a single quote and a red light stops it.
Narration: the default xargs splits on whitespace and also interprets quotes; a single weird name can derail a bulk operation halfway.
Shot 3 · 45–70s
Visual: find puts a “null byte” block after each name; xargs recognizes only that block, loads each name whole into an argv car, and dispatches the train once it is full.
Narration: -print0 pairs with -0; the null byte, which can never appear in a file name, separates items, and runs happen in batches up to the argument limit.
Shot 4 · 70–90s
Visual: rm -- "$f" the two dashes act like a gate, blocking -rf.txt a file name starting with a dash from being treated as an option.
Narration: finally, don't forget the double dash; it tells the command that everything after it is a file name.
or score ≥ 70% on the quiz

Module 5 · Sorting and set operations: sort, uniq, join, comm, cut, paste

28:00 – 35:00 · Treat text lines as sets: intersection, difference, join, grouped counts — provided they are “sorted by the same rule”
7 minGNU coreutils / uutils 0.8.0Watch the locale★★★★☆
Learning objectives
  • Use sort -t -k precisely specify sort keys (numeric n, version V, human-readable h, reverse r, de-duplicate -u, stable -s).
  • Understand uniq only merges adjacent duplicate lines; comm,join requires input sorted by the same collation — in scripts, always set LC_ALL=C.
  • Use comm for difference/intersection, use join to join two files by key, use cut/paste to pick columns and paste columns; know the differences introduced by the Rust coreutils in Ubuntu 26.04, and how to handle them.
Prerequisites: Modules 1–3. Importance:★★★★☆

What: line-oriented set tools

This group of tools treats “a line” as one element: sort sort (external merge sort, can handle files larger than memory),uniq merges adjacent duplicate lines,comm compares two sorted files and outputs three columns (left only / right only / common),join joins lines of two sorted files on a shared key (similar to SQL JOIN),cut selects columns,paste pastes lines side by side.

Why: typical ops problems

  • “Which hosts are in the inventory but not in monitoring?” —comm -23 (difference).
  • “The 10 busiest IPs?” —sort | uniq -c | sort -rn | head.
  • “Join the host inventory with the kernel version table to find unpatched machines” —join.

How: collation decides everything

sort String comparisons use LC_COLLATE (overridden by LC_ALL ). Under en_US.UTF-8 , case and punctuation follow language rules (for example a A b B), while under C/POSIX , comparison is by byte value (A B _ a b). comm,join,uniq also use the current locale to decide “sorted / equal”. As long as the locale used for sorting differs from the one used for comparing, you get “file 1 is not in sorted order” — or worse, silently wrong results.

OptionMeaningPitfall
-t, -k2,2Comma-separated; field 2 (from 2 to 2) is the keyOnly specifying -k2 means “from field 2 to end of line”
-k3,3n -k1,1reach key can have its own type and directionGlobal -n/-r applies to all keys that have no options of their own
-V -hversion numbers (1.9 < 1.10), human-readable sizes (2K < 1M)GNU extension (uutils also supports it)
-u -s -zkeep one line per equal key / stable sort / NUL-delimited-u De-duplicate by key, not by whole line
uniq -c -d -u -icount / show only duplicates / show only unique / ignore casemust sort first
comm -1 -2 -3hide columns 1/2/3-23 = left only; -13 = right only; -12 = intersection
join -t, -1 N -2 M -a1 -e X -o …specify separator and key columns, keep unmatched lines, fill empty values, output columnsboth inputs must be sorted by key; the header is treated as data

When: when not to use them

For multi-key joins, aggregation or missing-value handling, awk's NR==FNR associative arrays (no sorting needed), Miller (mlr join) or SQLite / DuckDB is clearer; for JSON data, use jq's group_by/INDEX.

Rust coreutils in Ubuntu 26.04 The default in 26.04 sort/uniq/comm/join/cut/paste come from uutils coreutils 0.8.0 (cp/mv/rm still GNU). Launchpad already has related reports, for example #2152822 “comm and sort are incompatible in 26.04 LTS” (under a non-C locale, comm judges sort's output as unsorted), and sort -k key-boundary whitespace handling inconsistent with GNU. Mitigations: ① in scripts, always set export LC_ALL=C; ② always use -t explicit separators,-kN,N explicit key ranges; ③ use sort --version to confirm the implementation, and install coreutils-from-gnu to switch back to GNU (per Ubuntu's official notes); ④ lock in expected output with tests (Lesson 7, bats).
Common misconceptions① “uniq removes all duplicate lines” — it only merges adjacent ones, so unsorted data must first be sort -u sorted or use awk '!seen[$0]++'. ② “sort -n can sort IPs”—10.0.0.10 is treated as the number 10.0; use sort -t. -k1,1n -k2,2n -k3,3n -k4,4n or sort -V. ③ “cut -d, can handle CSV” — quoted commas will misalign columns (Module 7).
inv.txt (inventory)monitored.txt (monitoring) bastion-01@proddb-01@devedge-01@prod 9 in commonweb-01@dev …db-01@prod cache-01@prod comm -23 → column 1: left onlycomm -12 → column 3comm -13 → column 2: right only Prerequisitesboth sides sortedand same localeLC_ALL=C sortLC_ALL=C comm
Figure 5-1: comm's three columns are the two set differences and the intersection (keys are name@env; actual output)
Left: ip,host@env (sorted) 10.10.1.21,web-01@dev10.10.1.22,api-01@dev10.10.1.23,db-01@dev10.20.1.31,web-01@staging… 12 lines in total Right: ip,request count (sorted) 10.10.1.21,5810.10.1.22,6410.20.1.31,51172.16.5.4,63 … Output (two pointers advance in step) 10.10.1.21,web-01@dev,5810.10.1.22,api-01@dev,6410.20.1.31,web-01@staging,51-a1 -e 0: keep the left sideunmatched lines and fill with 0 The merge algorithm scans only once, so both sides must be sorted by the same rule; when unsorted, GNU join reports “is not sorted”
Figure 5-2: join's merge-style association (similar to SQL's sort-merge join)

Interactive: sort | uniq -c | sort -rn Pipeline and comm

Data is column 1 of the first 20 lines of access.log (head -20). Step through the pipeline to see why “running uniq without sorting” gives wrong counts, and the real output at each step (actual output, LC_ALL=C).

Ready.
$ awk '{print $1}' data/access.log
cd ~/bashlab/data && export LC_ALL=C
# Status code distribution: count descending first, then status code ascending (deterministic output order)
awk '{print $9}' access.log | sort | uniq -c | sort -k1,1nr -k2,2n

# uniq without sorting: only adjacent lines merge → wrong result
awk '{print $1}' access.log | uniq -c | head -4
    450 200
     54 201
     22 304
     19 302
     12 301
     12 500
     12 503
     11 400
      9 404
      6 401
      4 502
      1 203.0.113.7
      1 192.0.2.10
      1 172.16.5.4
      1 10.10.1.22

Without sorting, uniq -c it produced 538 lines (11 IPs should give only 11 lines).

# Sort IPs and version numbers
printf '10.0.0.10\n10.0.0.9\n10.0.0.100\n' | sort -t. -k1,1n -k2,2n -k3,3n -k4,4n
printf '1.10.0\n1.9.3\n1.10.0-rc1\n' | sort -V

# Multi-key: env ascending, name descending within the same env (the header also gets sorted!)
sort -t, -k2,2 -k1,1r servers.csv | head -4
# Keep the header:
{ head -n1 servers.csv; tail -n +2 servers.csv | sort -t, -k2,2 -k1,1r; } | head -3
10.0.0.9
10.0.0.10
10.0.0.100
1.9.3
1.10.0
1.10.0-rc1
web-01,dev,canadacentral,10.10.1.21,web
db-01,dev,canadacentral,10.10.1.23,db
api-01,dev,canadacentral,10.10.1.22,api
name,env,region,ip,role
name,env,region,ip,role
web-01,dev,canadacentral,10.10.1.21,web
db-01,dev,canadacentral,10.10.1.23,db

The env column of the header is a string env, by byte order it sorts after dev and before prod — it sits right in the middle of the data.

sort -V Putting 1.10.0-rc1 sorts 1.10.0 after (the shorter prefix comes first) — this is the opposite of the SemVer rule (pre-release versions sort before the release). When comparing version numbers with pre-release tags, use a dedicated tool or dpkg --compare-versions (Debian version rules use ~ to mark pre-releases: 1.10.0~rc1).

# comm: inventory vs monitoring. Host names repeat across environments (web-01 has 3 hosts), so the key must be name@env
tail -n +2 servers.csv | cut -d, -f1,2 | tr , @ | sort > /tmp/inv.txt
printf '%s\n' web-01@dev api-01@dev web-01@staging api-01@staging db-01@staging \
              web-01@prod web-02@prod api-01@prod db-01@prod cache-01@prod | sort > /tmp/monitored.txt
comm -23 /tmp/inv.txt /tmp/monitored.txt      # in inventory, not monitored
comm -13 /tmp/inv.txt /tmp/monitored.txt      # monitored, but not in inventory (decommissioned?)
comm -12 /tmp/inv.txt /tmp/monitored.txt | wc -l
bastion-01@prod
db-01@dev
edge-01@prod
cache-01@prod
9

If only host names are used as keys,sort -u after that only 6 names remain, and the fact that “db-01@dev is not monitored” gets masked by db-01@staging — choosing the key matters more than choosing the command.

# join: inventory (IP → host@env) joined with the request count per IP in the access log (strip header, sort by key, explicit output columns)
awk '{print $1}' access.log | sort | uniq -c | awk '{print $2","$1}' | sort -t, -k1,1 > /tmp/hits.csv
join -t, -a1 -e 0 -o 0,1.2,2.2 \
  <(tail -n +2 servers.csv | awk -F, '{print $4","$1"@"$2}' | sort -t, -k1,1) \
  /tmp/hits.csv
10.10.1.21,web-01@dev,58
10.10.1.22,api-01@dev,64
10.10.1.23,db-01@dev,0
10.20.1.31,web-01@staging,51
10.20.1.32,api-01@staging,0
10.20.1.33,db-01@staging,0
10.30.1.41,web-01@prod,0
10.30.1.42,web-02@prod,0
10.30.1.43,api-01@prod,0
10.30.1.44,db-01@prod,0
10.30.2.10,bastion-01@prod,0
10.30.2.51,edge-01@prod,0

-a1 keep left-side lines that have no match,-e 0 fill in missing counts. Only 3 internal servers appear in the access log — they appear as clients calling the API (the Module 8 postmortem uses 10.20.1.31).

# cut / paste
cut -d, -f1,4 servers.csv | head -3        # take columns 1 and 4
cut -c1-15 access.log | head -2             # by character position
tail -n +2 servers.csv | cut -d, -f1 | paste -sd, -   # join multiple lines into one line
paste -d, <(seq 3) <(printf 'a\nb\nc\n')    # two columns side by side
grep -oE '^[0-9.]+|" [0-9]{3} ' access.log | paste - - | head -2   # join every two lines into one
name,ip
web-01,10.10.1.21
api-01,10.10.1.22
203.0.113.7 - -
192.0.2.10 - -
web-01,api-01,db-01,web-01,api-01,db-01,web-01,web-02,api-01,edge-01,db-01,bastion-01
1,a
2,b
3,c
203.0.113.7	" 200
192.0.2.10	" 200 
How to verify / Common errors / Production use Verify: sort -c file (checks whether the input is sorted; exit code 1 means unsorted); sort --debug -t, -k2,2 f (GNU) draws the keys actually used under each line. Common errors: forgetting to strip the header; running sort and comm under different locales; sort -k2 not specifying the key's end field. Production use: asset inventory reconciliation, patch compliance reports, log Top N.

Lab 5: Asset reconciliation report

Goal: Use comm and join to answer: which hosts are not monitored, which monitored targets are no longer in the inventory, and which servers appear in the access log. Environment: data from make-data.sh + files created by the commands on this page /tmp/inv.txt,/tmp/monitored.txt,/tmp/hits.csv. Cleanup:rm -f /tmp/inv.txt /tmp/monitored.txt /tmp/hits.csv /tmp/l1.txt /tmp/l2.txt /tmp/s1.txt /tmp/s2.txt.

Reproduce the locale-mismatch error
printf 'aa\nAa\nab\nAb\n' > /tmp/l1.txt; printf 'aa\nAb\n' > /tmp/l2.txt
LC_ALL=en_US.UTF-8 sort /tmp/l1.txt > /tmp/s1.txt; LC_ALL=en_US.UTF-8 sort /tmp/l2.txt > /tmp/s2.txt
LC_ALL=C comm -12 /tmp/s1.txt /tmp/s2.txt
comm: file 1 is not in sorted order
…

If the system has not generated en_US.UTF-8 (locale -a check), you can use sudo locale-gen en_US.UTF-8. Fix: set both sides to the same LC_ALL=C.

Generate the reconciliation report
export LC_ALL=C
cd ~/bashlab/data
{
  echo "## Hosts not monitored"; comm -23 /tmp/inv.txt /tmp/monitored.txt
  echo "## Monitored but not in inventory"; comm -13 /tmp/inv.txt /tmp/monitored.txt
  echo "## Servers that appear as clients in the access log"
  join -t, -o 0,1.2,2.2 \
    <(tail -n +2 servers.csv | awk -F, '{print $4","$1"@"$2}' | sort -t, -k1,1) \
    /tmp/hits.csv
}
## Hosts not monitored
bastion-01@prod
db-01@dev
edge-01@prod
## Monitored but not in inventory
cache-01@prod
## Servers that appear as clients in the access log
10.10.1.21,web-01@dev,58
10.10.1.22,api-01@dev,64
10.20.1.31,web-01@staging,51
Check which sort implementation you are using
sort --version | head -1
ls -l "$(command -v sort)"
sort (uutils coreutils) 0.8.0
lrwxrwxrwx 1 root root … /usr/bin/sort -> …

Case 1: reconciliation script fails after upgrading to Ubuntu 26.04

Symptom: The daily “inventory vs CMDB” script starts reporting comm: file 1 is not in sorted order. Cause: The script does not set a locale, and the cron environment's LANG differs from interactive shells. Also, 26.04's sort is now uutils, and its collation details do not match comm (Launchpad #2152822). Fix: At the top of the script, export LC_ALL=C, and add bats test cases covering mixed case and punctuation.

Case 2: Top 10 IPs come out in a different order each run

Cause: IPs with equal counts have undefined order (sort -rn numeric sort only). As a result, the diff in the alert message keeps changing. Fix:sort -k1,1nr -k2,2 Add a secondary sort key so the output is deterministic.

Case 3: sorting a large file fills up /tmp

Cause: GNU sort writes temporary files for data that exceeds its memory buffer to $TMPDIR (default /tmp). Fix:sort -S 1G -T /data/tmp --parallel=4; or first aggregate with awk (an associative array stores only the distinct keys) and then sort, cutting the data volume by orders of magnitude.

comm: file 1 is not in sorted order

Cause: The input is not sorted, or the locale differs between sorting and comparison. Diagnose:LC_ALL=C sort -c f1; echo $?. Fix:LC_ALL=C comm -23 <(LC_ALL=C sort -u a) <(LC_ALL=C sort -u b).

join: /dev/fd/63:2: is not sorted: a,2

Cause: join input is not sorted by the join key (or was sorted by whole line instead of by the key field). Fix:sort -t, -k1,1, and keep join's -t consistent; --nocheck-order Silencing the warning only hides it; it does not fix the result.

uniq -c shows more lines than expected (the same IP appears multiple times)

Cause: there is no sort before uniq, or the lines have invisible characters at the end (\r, trailing spaces). Diagnose:… | cat -A | head. Fix:sort; sed 's/\r$//'; or count with an awk associative array.

sort: write failed: /tmp/sortXXXX: No space left on device

Cause: The external sort's temporary files filled up /tmp. Fix:-T point it at a large disk,-S increase the memory buffer, or aggregate before sorting.

cut: the delimiter must be a single character

Cause:cut -d It accepts only a single character (tab is the default). Fix: For multi-character or regex separators, use awk -F'::'; for whitespace-separated columns, use awk '{print $2}' (cut treats every space as a separator).

Command questions

1. Find the paths that appear only once in access.log (strip the query string).
awk '{ p=$7; sub(/\?.*/, "", p); print p }' data/access.log | LC_ALL=C sort | uniq -u
# No output: in this data, all 6 paths appear 63 or more times; uniq -c can confirm this
2. Print the count of hosts per region in servers.csv, in the format “region=count”, sorted by region (the quoted comma on line 11 is in column 5 and does not affect column 3).
tail -n +2 data/servers.csv | cut -d, -f3 | LC_ALL=C sort | uniq -c | awk '{print $2"="$1}'
# ca-central-1=5
# canadacentral=7

Scenario analysis

You need to compare two IP lists of 20 million rows each every day and find the newly added IPs. A colleague suggests grep -vxFf old.txt new.txt. Evaluate it and propose a solution.

grep -Ff would load 20 million patterns into memory to build an automaton, so memory and time costs are very high; comm -13 <(LC_ALL=C sort -u old) <(LC_ALL=C sort -u new) is an O(n log n) sort plus one linear merge; the sort can use -S/-T/--parallel to control resources; if old was already sorted and saved yesterday, you only need to sort new. You can also use awk 'NR==FNR{a[$0];next} !($0 in a)' old new (keeps all keys of old in memory; suitable for medium-sized data).

Verified instructional videos

▶
Lecture 4: Data Wrangling (2020) — Missing Semester
English · Demo sort | uniq -c | sort -nr, paste, and awk in real-data analysis

No verified video specifically on comm / join was found; rely on this module's diagrams and the documents below.

Official documentation

Video storyboard script (about 75 seconds)

This courseware cannot generate video or MP3 directly. A storyboard and narration script are provided for a video tool to produce it.

Shot 1 · 0–20s
Visual: 20 IP cards shuffled into a column; uniq merges only adjacent cards, so the same IP appears twice.
Narration: uniq only looks at adjacent lines, so you must sort first.
Shot 2 · 20–45s
Visual: after sorting, the cards cluster into groups; uniq -c stamps each group with a number, then the groups are arranged into a podium by count, descending.
Narration: sort, count, sort again — the most common Top N pattern on the command line.
Shot 3 · 45–75s
Visual: two overlapping circles; comm's three columns light up in turn. Beside them, a locale switch goes from English to C, the sort order changes, and comm flashes red with an error.
Narration: comm and join require both sides to be sorted by the same rules. In scripts, set LC_ALL to C consistently.
or score ≥ 70% on the quiz

Module 6 · JSON and YAML: jq and yq

35:00 – 42:00 · Don't cut structured data with grep/sed: read and write it by path, using tools that understand the structure
7 minjq 1.8.1 (Ubuntu) / 1.8.2yq v4.54.3 (mikefarah)★★★★★
Learning objectives
  • Understand jq's value-stream model: a filter takes one value and produces zero or more values,| feeding each output stream into the next filter one by one.
  • Be proficient with .[],select,map,group_by, object construction,// defaults, and -r,-c,-e,--arg/--argjson,@tsv/@csv/@sh.
  • Use mikefarah yq v4 to read and edit YAML in place (-i,strenv), convert between YAML / JSON / CSV, and know how it differs from the Python version in Ubuntu's repository yq .
Prerequisites: NUL-delimited input from Module 4 and TSV from Module 5. Importance:★★★★★ (cloud CLIs, Kubernetes and CI configs are almost all JSON/YAML)

What: jq and yq

jq (jqlang/jq, written in C) is a command-line processor for JSON with a small functional language in which everything is a filter,. is the identity filter,.name gets a field,.[] turns an array into multiple output values,a | b feeds each output of a into b. yq (mikefarah/yq, written in Go) uses jq-like syntax to process YAML (it also supports JSON, XML, CSV/TSV, TOML, properties), and can edit in place while preserving comments and formatting as much as possible.

Why: why not use grep/sed/awk on JSON/YAML

  • JSON can be on one line or formatted into any number of lines; key order, whitespace and escapes (\",é) are not fixed — line-based tools have no stable 'columns'.
  • YAML has indentation, anchors, multi-document files and several scalar styles ("yes" and yes have different types) — sed can corrupt the structure with almost no error until the application fails to start.
  • jq/yq can validate input (invalid JSON exits directly with code 2 or 5), moving errors earlier into the script.

How: common building blocks

jq expressionMeaningSample output
.[] | .nameExpand the array, take each element's name12 strings
select(cond)Outputs the input if cond is true, otherwise outputs “empty”Filter
map(f)equivalent to [.[] | f]array → array
{name, ip},{(.name): .ip}object construction (shorthand / dynamic keys){"web-01":"10.10.1.21"}
group_by(.env),unique,length,addgrouping, de-duplication, length, mergingAggregate
.a // "default"uses the right side when the left is null/false or produces no outputDefault value
test("re"),sub,ascii_downcase,trim (available in jq 1.8)String functions (regex is Oniguruma, similar to PCRE)Match
@tsv @csv @sh @json @base64Format as TSV / CSV / shell-safe quoting / JSON string / base64Hand off to shell or awk
OptionEffectMeaning in scripts
-r / -jPrint strings raw (no quotes) / strip newlinesalmost always needed when passing output to other commands -r
--raw-output0 (jq 1.7+)follow each output with NULwith xargs -0 / read -d '' for safe handoff
-c / -SCompact one line / sort keysUse for diffs -S stable output
-eExit code 1 if the last output is false/null, 4 if there is no output at allUse in conditionals
--arg k v / --argjson k jsonPass a value into a variable as a string / JSON value $kNever splice shell variables into the jq program string
-n / -sDon't read input / collect all input into one arrayBuild JSON, merge multiple files

When: which yq?

mikefarah/yq (used in this lesson)kislyuk/yq (Ubuntu's apt install yq, 3.4.3)
ImplementationGo single binary, with built-in jq-style syntaxPython, converts YAML to JSON and then calls jq
Identify byyq --version containing “mikefarah” and v4.xyq --version shows 3.x
In-place edityq -i, preserving comments where possible-i (needs -y to output YAML), comments are lost
InstallGitHub Release binary, snap, Homebrewapt / pip
Common misconceptions① “jq ".[] | select(.env==\"$env\")" is fine” — quotes or backslashes in a variable inject jq code; use --arg env "$env". ② “yq commands are the same” — two tools with the same name have incompatible syntax, so check which one is installed in the CI image first. ③ “jq's -r output can be used directly in a for loop” — values may contain spaces or newlines; use @tsv + while IFS=$'\t' read -r, or --raw-output0.
Input: 1 array12 objects .[]1 → 12 values select(.env=="prod")12 → 6 (6 become empty) {name, ip}6 → 6 stdout “|” is not a shell pipe: it runs inside the jq process and passes each every single output value separately to the right side To collect results into an array, use [ … ]: [.[] | select(…)] | length
Figure 6-1 jq value flow: a filter can output 0, 1 or multiple values
config.yamlopsctl: log_level: info # …environments: prod: region: canadacentral yq parses into a node treePreserved: comments, key order,scalar style (quotes)locate nodes by path.opsctl.log_level Assign= strenv(LEVEL)|= . * 2del(.x) -i writes backre-serialize(indentation maybe normalized)
Figure 6-2 yq read-modify-write: based on a node tree rather than text lines

Value flow in a jq filter pipeline

Program: jq -c '.[] | select(.env == "prod") | {name, ip}' data/inventory.json. Step through each filter stage's input and output values (the data and outputs are actual results from this lesson's sample).

Ready.
$ jq -c '.[] | select(.env == "prod") | {name, ip}' data/inventory.json

jq: inventory.json

cd ~/bashlab/data
jq '.[6]' inventory.json
jq -r '.[] | select(.env == "prod") | .name' inventory.json
{
  "name": "web-01",
  "env": "prod",
  "region": "canadacentral",
  "ip": "10.30.1.41",
  "role": "web"
}
web-01
web-02
api-01
edge-01
db-01
bastion-01
# Passing arguments: --arg (string) / --argjson (number, boolean, object)
env=staging
jq -r --arg env "$env" '.[] | select(.env == $env) | "\(.name) \(.ip)"' inventory.json
jq -nc --argjson n 3 '{replicas: $n}'

# Group count
jq -c 'group_by(.env) | map({env: .[0].env, count: length, hosts: map(.name)})' inventory.json

# Dynamic keys: name → IP mapping (watch out for duplicate names!); de-duplicated concatenation
jq -c 'map({(.name): .ip}) | add' inventory.json
jq -c 'map({(.name + "@" + .env): .ip}) | add | length' inventory.json
jq -r 'map(.env) | unique | join(",")' inventory.json
web-01 10.20.1.31
api-01 10.20.1.32
db-01 10.20.1.33
{"replicas":3}
[{"env":"dev","count":3,"hosts":["web-01","api-01","db-01"]},{"env":"prod","count":6,"hosts":["web-01","web-02","api-01","edge-01","db-01","bastion-01"]},{"env":"staging","count":3,"hosts":["web-01","api-01","db-01"]}]
{"web-01":"10.30.1.41","api-01":"10.30.1.43","db-01":"10.30.1.44","web-02":"10.30.1.42","edge-01":"10.30.2.51","bastion-01":"10.30.2.10"}
12
dev,prod,staging

The first mapping has only 6 keys: web-01, api-01 and db-01 each have 3 hosts,add when merging objects,the later one overrides the earlier one, leaving only the prod IPs — silent data loss. Using name@env as the key gives the full 12 entries.

# Hand to shell: @tsv + while read (tab and newline characters inside fields are escaped as \t \n)
jq -r '.[] | [.name, .ip, .role] | @tsv' inventory.json |
while IFS=$'\t' read -r name ip role; do
  printf '%-12s %-12s %s\n' "$name" "$ip" "$role"
done | head -3

# @csv: automatically quotes strings (the role of the 10th object is "web,api")
jq -r '.[] | [.name, .role] | @csv' inventory.json | tail -1
jq -r '.[9] | [.name, .role] | @csv' inventory.json      # "edge-01","web,api"

# jq 1.7+: NUL-delimited output, pipes directly into xargs -0
jq --raw-output0 '.[] | select(.env == "prod") | .name' inventory.json | xargs -0 -n1 echo host:
web-01       10.10.1.21   web
api-01       10.10.1.22   api
db-01        10.10.1.23   db
"bastion-01","bastion"
host: web-01
host: web-02
host: api-01
host: edge-01
host: db-01
host: bastion-01
# -e: turns “exists or not” into an exit code
if jq -e --arg n edge-01 'any(.[]; .name == $n)' inventory.json >/dev/null; then echo "edge-01 is in the inventory"; fi
jq -e '.[] | select(.name == "nope")' inventory.json; echo "rc=$?"     # no output → 4

# Default values and modification (jq does not write files in place: write a temp file, then mv)
echo '{"a":null}' | jq -r '.a // "default"'
tmp=$(mktemp) && jq '.[0].ip = "10.10.1.99"' inventory.json > "$tmp" && jq -r '.[0].ip' "$tmp"; rm -f "$tmp"
edge-01 is in the inventory
rc=4
default
10.10.1.99

yq (mikefarah v4): config.yaml

yq '.opsctl.log_level' config.yaml                    # end-of-line comments do not affect the value
yq '.environments.prod.region' config.yaml
yq '.environments | keys | .[]' config.yaml          # keys of the mapping
yq '.health.backoff_seconds[]' config.yaml
yq -o=json -I=0 '.environments.staging' config.yaml   # YAML → JSON (compact)
yq '.environments.prod.require_confirm | tag' config.yaml
info
canadacentral
dev
staging
prod
1
2
4
{"region":"ca-central-1","health_url":"http://10.20.1.31:8080/healthz"}
!!bool
# In-place edit: value comes from an env var (strenv keeps it as a string; env parses it as YAML types)
cp config.yaml /tmp/c.yaml
LEVEL=debug yq -i '.opsctl.log_level = strenv(LEVEL)' /tmp/c.yaml
yq -i '.health.retries = 5' /tmp/c.yaml
yq -i '.backup.keep |= . * 2' /tmp/c.yaml
diff config.yaml /tmp/c.yaml

# Format conversion
yq -p=json -o=yaml '.[0]' inventory.json         # JSON → YAML
yq -p=csv -o=json '.[9]' servers.csv             # CSV → JSON (handles quoted commas correctly)
4c4
<   log_level: info            # debug | info | warn | error
---
>   log_level: debug # debug | info | warn | error
20c20
<   retries: 3
---
>   retries: 5
24c24
<   keep: 7
---
>   keep: 14
name: web-01
env: dev
region: canadacentral
ip: 10.10.1.21
role: web
{
  "name": "edge-01",
  "env": "prod",
  "region": "ca-central-1",
  "ip": "10.30.2.51",
  "role": "web,api"
}
How to verify / Common errors / Production use Verify: jq empty file.json / yq 'true' file.yaml >/dev/null Syntax check only; compare before and after edits with diff <(jq -S . a) <(jq -S . b) . Common errors: forgetting -r causes strings to be passed downstream with quotes; a jq program in double quotes gets expanded by the shell $var; do not use the Python yq's syntax on the mikefarah version. Production use: az … -o json | jq / aws … --output json | jq (or directly use the CLI's --query JMESPath), editing Helm values and Kubernetes manifests, and parsing API responses in GitHub Actions.

Lab 6: Have opsctl read YAML config and JSON inventory

Goal: Write two reusable shell functions: read settings from config.yaml, and list hosts per environment from inventory.json. Environment: jq and mikefarah yq. Cleanup:rm -f /tmp/c.yaml.

Check dependencies (exit code 3 = missing dependency)
cd ~/bashlab
yq --version | grep -q mikefarah || { echo "Requires mikefarah/yq v4" >&2; exit 3; }
jq --version
Read config (use default when the path does not exist)
cfg::get() {   # cfg::get <yq path> [default]
  local v
  v=$(yq "$1" data/config.yaml) || return 1
  [[ $v == null || -z $v ]] && v=${2:-}     # when the path does not exist, yq prints null
  printf '%s\n' "$v"
}
cfg::get .opsctl.log_level
cfg::get .health.timeout_seconds
cfg::get .opsctl.timeout 30
info
5
30

Here the yq path is written into the program: the path comes from the script author, which is acceptable; values from user input must use strenv() to pass them in. Note: opsctl's own runtime configuration follows the Lesson 3 etc/opsctl.conf + config::get; config.yaml config.yaml is a sample file for yq practice and later lessons.

List hosts per environment (safe argument passing + TSV)
inv::hosts() {   # inv::hosts <env>
  jq -r --arg env "$1" '.[] | select(.env == $env) | [.name, .ip] | @tsv' data/inventory.json
}
inv::hosts prod | while IFS=$'\t' read -r name ip; do echo "$name → $ip"; done
web-01 → 10.30.1.41
web-02 → 10.30.1.42
api-01 → 10.30.1.43
edge-01 → 10.30.2.51
db-01 → 10.30.1.44
bastion-01 → 10.30.2.10
Edit config in place and verify it is still valid YAML
cp data/config.yaml /tmp/c.yaml
NEW=warn yq -i '.opsctl.log_level = strenv(NEW)' /tmp/c.yaml
yq '.opsctl.log_level' /tmp/c.yaml && yq 'true' /tmp/c.yaml >/dev/null && echo "YAML OK"
warn
YAML OK

Case 1: generate a host inventory from cloud CLI output

# Azure: names and private IPs of all running VMs (az's -d also queries power state and IPs)
az vm list -d -g rg-bash-lab -o json |
  jq -r '.[] | select(.powerState == "VM running") | [.name, .privateIps] | @tsv'
# AWS: the same requirement
aws ec2 describe-instances --filters Name=instance-state-name,Values=running --output json |
  jq -r '.Reservations[].Instances[] | [(.Tags // [] | from_entries.Name // "-"), .PrivateIpAddress] | @tsv'

Limitations: Output field names follow each CLI's current version (examples were not run against a real subscription); for simple field filtering you can also use the CLI's built-in --query (JMESPath), which means one less dependency.

Case 2: sed edit to YAML breaks a release

Problem: The pipeline uses sed -i "s/tag: .*/tag: $TAG/" values.yaml to update the image tag, but the sidecar's tag also got changed. Fix:TAG="$TAG" yq -i '.image.tag = strenv(TAG)' values.yaml, editing precisely by path. Limitations: yq rewriting may normalize indentation and quote style, so the first introduction produces a one-time formatting diff.

Case 3: error rate from JSON logs

# App emits JSON Lines: {"ts":"…","status":503,"path":"/api/orders",…}
jq -s 'length as $n | (map(select(.status >= 500)) | length) as $e | {total: $n, err: $e, rate: ($e / $n)}' app.jsonl
# For large files, avoid -s (it loads everything into memory); use reduce instead:
jq -n 'reduce inputs as $r ({n:0, e:0}; .n += 1 | .e += (if $r.status >= 500 then 1 else 0 end))' app.jsonl
jq: error (at inventory.json:0): Cannot index array with "name"

Cause: the input is an array, but it is used directly in .name. Fix:.[].name or map(.name). Conversely, “Cannot iterate over null” means .[] was applied to a field that does not exist; use .items[]? or (.items // [])[].

parse error: Invalid numeric literal at line 1, column 10

Cause: the input is not JSON (common cases: the CLI printed a table or warning text to stdout, an HTML error page, or YAML). Diagnose:head -c 200 file. Fix: For the CLI, add -o json/--output json; for curl, add -f and check the HTTP status; use yq for YAML.

Error: unknown command "…" for "yq" / yq: error: argument files: can't open '.opsctl'

Cause: you installed the Python yq (kislyuk), or a very old mikefarah v3 (which requires yq r file path). Diagnose:yq --version,command -v yq,dpkg -S "$(command -v yq)". Fix: Install the mikefarah v4 binary into /usr/local/bin and make sure it takes precedence in PATH.

jq: error: env/0 is not defined at <top-level> / $env is not defined

Cause: the jq program uses double quotes,$env is expanded to empty by the shell; or forgot --arg env …. Fix: always use single quotes for programs; pass variables with --arg; environment variables can use env.NAME / $ENV.NAME.

yq edits turned a boolean/number into a quoted string (or vice versa)

Cause:strenv() is always a string,env() is parsed as YAML (yes,08 and similar values are ambiguous). Fix: For numbers, use env(N) and validate first [[ $N =~ ^[0-9]+$ ]]; for strings, use strenv(); after editing, yq '.path | tag' file check the type tag (!!int,!!str).

Command questions

1. Output the number of prod hosts in each region, in the format region count.
jq -r 'map(select(.env == "prod")) | group_by(.region)[] | "\(.[0].region) \(length)"' data/inventory.json
# ca-central-1 2
# canadacentral 4
2. Multiply each item of health.backoff_seconds in config.yaml by 2, and output the array as compact JSON (do not modify the original file).
yq '.health.backoff_seconds[] |= . * 2 | .health.backoff_seconds' -o=json -I=0 data/config.yaml
# [2,4,8]

Scenario analysis

A colleague's script: for h in $(curl -s $API/hosts | jq .[].name); do ssh $h uptime; done. What problems does it have?

① No -r, host names contain quotes; ② command substitution and an unquoted loop get word-split and globbed; ③ .[].name is unquoted, so the shell may treat [] as a glob; ④ curl has no -f, so an HTTP error page is treated as JSON and fails, yet the loop keeps going (and $(…) failures inside it do not trigger errexit); ⑤ ssh consumes the loop's stdin (especially inside while read), so add -n. Rewrite: curl -fsS "$API/hosts" | jq -r '.[].name' | while IFS= read -r h; do ssh -n -- "$h" uptime; done, or use --raw-output0 + xargs -0 -P.

Verified instructional videos

No English video that was verified via YouTube oEmbed and specifically covers jq / mikefarah yq was found (most results were third-party mirrors or paid courses). Refer to:

▶
Lecture 4: Data Wrangling (2020) — Missing Semester
English · General approach to data wrangling (mainly text tools; jq is only briefly mentioned)

Official documentation

Video storyboard script (about 90 seconds)

This courseware cannot generate video/MP3 directly. Storyboard and narration script are provided for a video tool to produce it.

Shot 1 · 0–20s
Visual: the same JSON is first compressed into one line, then expanded to twenty lines; grep's 'columns' are completely different in the two forms.
Narration: JSON formatting is not fixed, so line-based processing is inherently fragile.
Shot 2 · 20–50s
Visual: the array box opens, seven objects roll out one by one, pass through the select gate, two turn transparent and vanish, and the remaining five are compressed into small cards with only name and ip.
Narration: in jq everything is a filter; the pipe sends each output value into the next filter, and select outputs nothing when the condition is not met.
Shot 3 · 50–75s
Visual: the YAML file becomes a node tree; yq follows the path to the log_level leaf, replaces the value, and writes the whole tree back, with comments intact.
Narration: yq edits YAML by path, much safer than sed; make sure you install the mikefarah version.
Shot 4 · 75–90s
Visual: Shell variables are placed into the --arg safe, rather than being spliced directly into the program string.
Narration: always pass values with --arg or strenv; never splice variables into the program.
or score ≥ 70% on the quiz

Module 7 · CSV and the boundaries of structured data

42:00 – 50:00 · “Comma-separated” is only the surface: quotes, escaped quotes and newlines inside fields make splitting on commas wrong — know when to switch tools
8 minRFC 4180 · gawk 5.3 --csvPython csv · Miller 6★★★★☆
Learning objectives
  • State the rules of RFC 4180 (fields may be wrapped in double quotes; commas and newlines inside quotes are data; "" a doubled double quote represents one double quote), and demonstrate cut -d,,awk -F, how each fails in these cases.
  • Master three correct ways to parse: gawk --csv (gawk 5.3+), Python standard library csv, Miller (mlr); and yq -p=csv conversion usage.
  • Use a decision table to identify when to switch between “shell text tools / dedicated CSV tools / a real programming language / a database”.
Prerequisites: Module 3 (awk FS), Module 6 (JSON). Importance:★★★★☆ (finance, asset and cloud billing exports are all CSV)

What: CSV is not “text separated by commas”

RFC 4180 (2005, Informational) describes the most common CSV dialect: records are separated by CRLF (LF is also common in practice); fields may be wrapped in double quotes; a quoted field can contain commas, newlines and double quotes; a double quote is written as two ""; the first line may be a header. In practice there are also semicolon-separated files (European Excel), tab-separated (TSV), UTF-8 with BOM, and different quoting and escaping rules, so “CSV” is really a family of dialects.

Why: why splitting on commas is wrong

Inputcut -d, / awk -F,Correct parsing
edge-01,…,"web,api" (line 11 of servers.csv)6 fields; the 5th is "web5 fields; the 5th is web,api
1,"say ""hi"""the 2nd field is "say ""hi""" (quotes included)say "hi"
2,"line1⏎line2"treated as two records1 record; a field contains a newline

How: the parser is a state machine

  1. Field start: on encountering " enter “in quotes”; on encountering , emit an empty field; otherwise enter “plain field”.
  2. plain field: on encountering , ends the field; a newline ends the record.
  3. in quotes: any character (including commas and newlines) is data; on encountering " enter “after quote”.
  4. after quote: on encountering " → outputs a literal quote and returns to “in quotes”; on encountering , or a newline → ends the field / record.

A regex cannot do “multi-line, stateful” processing, which is exactly why FPAT approach also fails when a field contains a newline.

When: when to switch tools (decision table)

SituationRecommendation
Simple data you generate yourself, certainly with no quotes or commas (e.g. servers.csv all lines except line 11)cut / awk -F, (but check at the entry point the field count)
External CSV (Excel exports, cloud bills, CMDB) — only filtering, selecting columns, sorting, countingMiller (mlr) or gawk --csv (gawk ≥ 5.3)
Needs type conversion, date handling, writing CSV back, complex logicPython csv module (standard library, no dependencies to install)
Multi-table joins, grouped aggregation, GB-scale dataSQLite (.import --csv), DuckDB or pandas
Needs conversion to JSON for an API / jqmlr --icsv --ojson,yq -p=csv -o=json, Python csv + json
Common misconceptions① “awk -v FPAT=… is a complete CSV parser” — FPAT can handle quoted commas, but not "" unescaping and newlines within fields (gawk 5.3 onwards: use --csv). ② “My data has no commas” — no commas today does not mean no commas tomorrow; validate at the entry point awk -F, 'NF!=5{exit 1}' validate it and stop on error. ③ “Converting CSV to JSON by adding brackets with sed is fine” — escaping (quotes, backslashes, control characters) almost always goes wrong; use a real serializer.
Field start Plain field In quotes After quote Output field /End record Other character " , or newline " "("" → literal quote) , or newline , ⏎ are all data next field
Figure 7-1 parsing state machine for RFC 4180-style CSV: quotes change the meaning of commas and newlines
cut / awk -F,Self-made, simple, validatedFastest, available everywhere gawk --csvgawk ≥ 5.3awk syntax + correct parsing Miller (mlr)Operate by column name, format conversionCSV/TSV/JSON/tables Python csv / SQLComplex logic, needs write-backMulti-table, aggregation, big data From left to right: correctness and expressiveness ↑, dependencies and startup cost ↑
Figure 7-2 ladder of tools for processing CSV

Naive splitting vs. CSV state machine: character-by-character comparison

Above is awk -F, the result (split on commas in one pass); below, the state machine from Figure 7-1 runs character by character. Orange marks the current character.

result of awk -F,
Input character
State
Field start
Current field buffer
(empty)
Parsed fields
Ready.
$ gawk --csv '{ for (i = 1; i <= NF; i++) print i": "$i }'
cd ~/bashlab/data && export LC_ALL=C
# Symptom: inconsistent field counts, column 5 truncated
awk -F, '{print NF}' servers.csv | sort | uniq -c
awk -F, '$2=="prod" {print $1, $5}' servers.csv | sed -n 4p
     12 5
      1 6
edge-01 "web
# Option 1: gawk 5.3's --csv (RFC 4180: quotes, "" unescaping, newlines inside fields)
gawk --csv 'NR>1 && $2=="prod" {print $1 " | " $5}' servers.csv
web-01 | web
web-02 | web
api-01 | api
edge-01 | web,api
db-01 | db
bastion-01 | bastion
# Option 2: Python standard library csv (handles quotes correctly for both reading and writing)
python3 - servers.csv <<'PY'
import csv, sys
w = csv.writer(sys.stdout, lineterminator="\n")
with open(sys.argv[1], newline="") as f:
    for r in csv.DictReader(f):
        if r["env"] == "prod":
            w.writerow([r["name"], r["role"]])
PY
web-01,web
web-02,web
api-01,api
edge-01,"web,api"
db-01,db
bastion-01,bastion
# Option 3: Miller (Ubuntu 26.04: apt install miller, version 6.16; upstream 6.22)
mlr --icsv --opprint filter '$env == "prod"' then cut -f name,role servers.csv
mlr --icsv --opprint count -g env then sort -nr count servers.csv
mlr --icsv --ojson filter '$name == "edge-01"' servers.csv
mlr --icsv --otsv cat servers.csv | cut -f5     # once converted to TSV, it is safe to hand off to cut/awk
name       role
web-01     web
web-02     web
api-01     api
edge-01    web,api
db-01      db
bastion-01 bastion

env     count
prod    6
dev     3
staging 3

[
{
  "name": "edge-01",
  "env": "prod",
  "region": "ca-central-1",
  "ip": "10.30.2.51",
  "role": "web,api"
}
]
role
web
…
# A trickier CSV: escaped quotes and newlines inside fields
printf 'id,note\n1,"say ""hi"""\n2,"line1\nline2"\n3,plain\n' > /tmp/tricky.csv
wc -l < /tmp/tricky.csv                                       # 5 lines, but only 4 records (including header)
awk -F, '{print NR": NF="NF}' /tmp/tricky.csv                  # 5 “records” ✗
gawk -v FPAT='([^,]*)|("[^"]*")' '{print NF": "$NF}' /tmp/tricky.csv   # FPAT also fails on newlines ✗
gawk --csv '{print NR": NF="NF" $2=["$2"]"}' /tmp/tricky.csv  # ✓
5
1: NF=2
2: NF=2
3: NF=2
4: NF=1
5: NF=2
2: note
2: "say ""hi"""
2: "line1
1: line2"
2: plain
1: NF=2 $2=[note]
2: NF=2 $2=[say "hi"]
3: NF=2 $2=[line1
line2]
4: NF=2 $2=[plain]
# Entry validation: reject a CSV that looks wrong in the script instead of silently computing wrong results
csv::check_simple() {   # usage: csv::check_simple FILE EXPECTED_COLS
  awk -F, -v n="$2" 'NF != n || /"/ { printf "line %d is not simple CSV (NF=%d)\n", NR, NF > "/dev/stderr"; bad = 1 } END { exit bad }' "$1"
}
csv::check_simple servers.csv 5 || echo "→ switch to gawk --csv / mlr / python"

# CSV → JSON (for jq)
python3 -c 'import csv, json, sys; print(json.dumps(list(csv.DictReader(open(sys.argv[1], newline="")))))' servers.csv | jq -r '.[9].role'
yq -p=csv -o=json '.[9].role' servers.csv
Line 11 is not simple CSV (NF=6)
→ switch to gawk --csv / mlr / python
web,api
web,api
How to verify / Common errors / Production use Verify: use Python csv.reader to count the fields on each line as the “ground truth” and compare against the shell results. Common errors: a CSV exported from Windows has a BOM (\xEF\xBB\xBF, so the first header name is wrong) and CRLF (the last column carries \r) —sed '1s/^\xEF\xBB\xBF//; s/\r$//' pre-process it, or use Python encoding="utf-8-sig". Production use: cloud bills (Azure Cost Management / AWS CUR exports), asset CMDB exports, permission audit reports.

Lab 7: correctly turn servers.csv into inventory.json, and compare with the existing file

Goal: Experience the consequences of parsing incorrectly, then get consistent results with three correct approaches. Environment: gawk ≥ 5.3, python3, jq; optionally miller, yq. Cleanup:rm -f /tmp/inv-*.json /tmp/tricky.csv.

Wrong approach: building JSON with awk
cd ~/bashlab/data
awk -F, 'NR>1 { printf "{\"name\":\"%s\",\"role\":\"%s\"}\n", $1, $5 }' servers.csv | sed -n 10p | jq .
parse error: Invalid numeric literal at line 1, column 31

The 10th data row (line 11)'s $5 is "web, producing {"name":"edge-01","role":""web"}, with unmatched quotes. Even when fields are correct, values containing quotes or backslashes generate invalid JSON.

Correct approach A: Python
python3 -c 'import csv, json, sys; json.dump(list(csv.DictReader(open(sys.argv[1], newline=""))), sys.stdout)' servers.csv > /tmp/inv-py.json
jq -r '.[9].role' /tmp/inv-py.json
web,api
Correct approach B: Miller; approach C: yq
mlr --icsv --ojson cat servers.csv > /tmp/inv-mlr.json
yq -p=csv -o=json servers.csv > /tmp/inv-yq.json
Compare all three with inventory.json to check whether they are semantically equal
for f in /tmp/inv-py.json /tmp/inv-mlr.json /tmp/inv-yq.json; do
  [[ -s $f ]] || continue
  if diff -q <(jq -S 'map(map_values(tostring))' inventory.json) <(jq -S 'map(map_values(tostring))' "$f") >/dev/null
  then echo "$f: consistent"; else echo "$f: different"; fi
done
/tmp/inv-py.json: consistent
/tmp/inv-mlr.json: consistent
/tmp/inv-yq.json: consistent

map_values(tostring) Smooth out type differences: Miller / yq may infer fields that look like numbers as numbers, while Python csv always yields strings. This is another boundary to watch when choosing a tool.

Case 1: cost allocation report missed one department

Problem: The monthly script uses awk -F, to sum column 12 (“cost”) of the cloud bill CSV. One resource group's tag value is "Finance, EMEA", so every column after that row shifts one position right, and the cost is added to the wrong column. Fix: Switch to mlr --icsv stats1 -a sum -f Cost -g Department, referencing by column name rather than by number; add a field-count check at the entry point. Limitations: Billing files can reach several GB. Miller streams them without problems; Python needs care not to read everything into memory at once.

Case 2: Excel-exported host inventory, “first column invisible” on Linux

Symptom:awk -F, '$1=="name"' the header is not found,jq '.[0] | keys' shows "name". Cause: UTF-8 BOM. Fix: Clean up uniformly at the entry point: sed -i.bak '1s/^\xEF\xBB\xBF//; s/\r$//' file.csv (GNU sed supports \xHH), or in Python use utf-8-sig.

Case 3: when to stick with the shell

If the CSV is generated by your own script (for example opsctl servers list --format csv), you can guarantee that fields contain no commas or quotes (validated or substituted at generation time). Then cut/awk is perfectly reasonable; the key is to write this convention into docs and tests rather than assume it.

awk field counts vary (NF=5 / NF=6)

Cause: quoted commas. Diagnose:awk -F, '{print NF}' f | sort | uniq -c; grep -n '"' f. Fix:gawk --csv / mlr / Python.

gawk: unrecognized option '--csv' / awk: not an option: --csv

Cause: gawk is older than 5.3, or awk is mawk. Diagnose:gawk --version | head -1. Fix: Ubuntu 26.04 apt install gawk (5.3.2 or later); on older systems use Miller or Python.

_csv.Error: field larger than field limit (131072)

Cause: Python csv's default per-field limit is 128 KiB; this often happens when unmatched quotes “swallow” the rest of the file. Diagnose: First find lines with unmatched quotes: awk -F'"' 'NF % 2 == 0 {print NR}' f (odd number of quotes in a single line). Fix: fix the data; if large fields are genuinely needed, raise the limit with csv.field_size_limit(10**7).

mlr: mlr: CSV header/data length mismatch 5 != 6

Cause: a row's field count differs from the header (the data itself is wrong, or a comma is genuinely missing or extra). Fix: fix the data; Miller 6 can use --allow-ragged-csv-input lenient handling (refer to the Miller docs).

The last-column comparison always fails ($5 == "web" is false)

Cause: CRLF line endings; the last field is web\r. Diagnose:head -2 f | od -c | head or cat -A. Fix:sed 's/\r$//' or, in awk, use sub(/\r$/, "").

Command questions

1. Use gawk --csv to output the host names in servers.csv whose role contains a comma.
gawk --csv 'NR>1 && index($5, ",") { print $1 "@" $2 }' data/servers.csv      # edge-01@prod
2. Find lines in a CSV file with an odd number of quotes (candidates for unmatched quotes).
awk -F'"' 'NF % 2 == 0 { print NR": "$0 }' file.csv
# With " as the separator, an even number of quotes yields an odd number of fields; an even NF means an odd number of quotes

Scenario analysis

Finance gives you a 300 MB CSV (exported from Excel, with a BOM, CRLF, and quoted company names) and asks you to summarize costs by department and output JSON for a dashboard. How would you choose the approach?

Don't use cut/awk -F,. Prefer Miller: mlr --icsv --ojson stats1 -a sum -f Cost -g Department (Miller handles CRLF; for the BOM follow the version's docs, and if needed first sed '1s/^\xEF\xBB\xBF//'). For more complex rules (exchange rates, date ranges, validation reports), use Python csv stream-read (encoding="utf-8-sig",newline=""), and output json. If you need repeated multi-dimensional analysis, import into SQLite/DuckDB. Either way, run regression tests in CI on a small sample (with quotes, nulls and non-ASCII).

Verified instructional videos

No English video verified via YouTube oEmbed that specifically covers “CSV boundaries / Miller / gawk --csv” was found. For reference, here are the verified data-wrangling videos for this lesson:

▶
Lecture 4: Data Wrangling (2020) — Missing Semester
English · covers ideas like “when to switch from shell tools to Python/R”

Official documentation

Video storyboard script (about 75 seconds)

This courseware cannot generate video/MP3 directly. Storyboard and narration script are provided for a video tool to produce it.

Shot 1 · 0–20s
Visual: a “comma scissors” cuts down a line of CSV, slicing "web,api" in two; the columns after it all shift right.
Narration: splitting on commas looks simple, but a quoted comma breaks everything.
Shot 2 · 20–50s
Visual: four-state machine circles; a light point advances character by character; once inside quotes, commas and newlines become plain grey characters.
Narration: real CSV parsing is a state machine; quotes change the meaning of commas and newlines.
Shot 3 · 50–75s
Visual: a four-step staircase: cut and awk, gawk --csv, Miller, Python and databases, each step labeled with its use case.
Narration: simple data you generate yourself can use awk; for external CSV, switch to a tool that understands CSV.
or score ≥ 70% on the quiz

Module 8 · opsctl logs: log analysis report

50:00 – 60:00 · Build the awk, sort, validation and exit-code conventions from this lesson into a new opsctl subcommand logs report
10 minopsctl v0.2 + logsPOSIX awk★★★★★
Learning objectives
  • Add, following opsctl conventions, lib/cmd_logs.sh: a function cmd::logs that dispatches subcommands,logs::report parses --top,--format and file arguments, and follows exit codes 0/1/2/3.
  • Write a single-pass awk report program (lib/logs_report.awk): total requests, bytes, skipped bad lines, status code distribution, Top N paths (including each path's 5xx count), 5xx error rate; supports text and tsv two output formats.
  • Understand the design trade-offs: why the awk program is in a separate file, why LC_ALL=C, why it supports - (standard input), and how to leave an interface for Lesson 7's tests.
Prerequisites: Module 3 (awk), Module 5 (sort), and the opsctl structure from Lessons 3–4. Importance:★★★★★

What: opsctl logs report

Usage: opsctl logs report [options] [FILE|-]
Summarize a combined-format access log: requests, status codes,
top paths and 5xx error rate. FILE defaults to <data_dir>/access.log;
'-' reads standard input (e.g. zcat access.log.1.gz | opsctl logs report -).
Options:
  -n, --top N          number of paths to show   (default: logs_top = 5)
  -f, --format FMT     text | tsv                (default: logs_format = text)
  -h, --help           show this help
Environment: OPSCTL_LOGS_TOP, OPSCTL_LOGS_FORMAT, OPSCTL_DATA_DIR.

Why: why make it a subcommand rather than a one-line awk

  • Consistent interface: the on-call runbook says opsctl logs report /var/log/nginx/access.log, anyone can run it; bad arguments print a hint and exit with 2,opsctl help and help lists it automatically.
  • Unified configuration: --top,--format follow Lesson 3's config::set_flag / config::get, so the same value can also come from OPSCTL_LOGS_TOP environment variables or etc/opsctl.conf in the logs_top = 10, error messages say where the value came from (add the two new keys to lib/cmd_config.sh 's for key in … list,opsctl config show also show where they come from).
  • Testable, composable: input (file / stdin) and output (stdout report, stderr logs, exit codes) are explicit, so Lesson 7 can assert with bats; --format tsv for machines to read,- so it can be fed into zcat downstream.

How: design decisions

DecisionChoiceRationale
Integration approachNew file lib/cmd_logs.sh, header # opsctl-summary:, functions cmd::logsbin/opsctl of opsctl::load_command auto-sourced and checked by name declare -F cmd::logs; the entry script needs no changes
Option valuesconfig::set_flag logs_top "$2", used at runtime, config::get logs_top top srcand servers list must match; new keys logs_top/logs_format are added to OPSCTL_DEFAULTS (defaults + allowlist); error messages can indicate whether a value came from the flag / env / file
Default fileconfig::get data_dir → <data_dir>/access.logReuse the existing data_dir keys (default $HOME/bashlab/data)
Compute engineone awk pass + associative arraysO(N) time; memory is proportional only to the number of distinct paths/status codes; compared with sort | uniq -c it avoids sorting all data
awk dialect and locationPOSIX awk, separate file lib/logs_report.awk,awk -fmawk / gawk / BusyBox awk all run it; avoids nested shell quoting; can be run separately with gawk --posix to check; ShellCheck does not raise false positives. The file is not named cmd_*.sh, so it is not treated as a subcommand
Fieldsonly uses $7 $9 $10the UA contains spaces (NF is 12/15/21/24), so it cannot be relied on; $9 must be a 3-digit status code, otherwise it is counted as skipped
Path normalizationstrip the query stringprevents ?page=N key cardinality from exploding; paths with IDs (/api/orders/1042) — see the troubleshooting tree
Sortinginside awk, print | "sort …" + close()for-in order is undefined; close() ensures sorted results are printed before the following printf
localeLC_ALL=Cbyte semantics, deterministic sorting, and faster; inherited by the sort that awk starts
Errorsutil::usage_error (EX_USAGE=2),util::die … "$EX_ERR" (1),util::require_cmd (EX_DEP=3)follow the opsctl exit code convention; all logs go through log::* to stderr
Strict mode (v0.2)awk is written as awk … || rc=$?, then branch on rcv0.2's entry point enables set -Eeuo pipefail and the ERR trap. If awk's “no valid lines” exit code 1 bubbled up directly, a stack trace would be printed; placing it after || to capture rc, then use util::die to give a readable one-line error; SIGPIPE (141,| head) returns quietly

When: its boundaries

Suitable for: single-machine logs or logs pulled locally, quick triage at the incident scene, cron periodic summaries. Not suitable for: real-time multi-host aggregation, analysis by UA or latency (the combined format has no latency field, so nginx must add $request_time), long-term trends — leave these to the log platform and Prometheus metrics.

Common misconceptions① “Error rate = 4xx + 5xx” — most 4xx are client-side issues (401s from brute force, 404s), and SLOs usually count only 5xx as server-side errors; this report counts only 5xx (28/611 = 4.58%), while the status distribution shows the 4xx. ② “An awk pipe | "sort" outputs immediately” — unless close() , sort waits until awk exits to output, so the order lands at the end of the report. ③ “Setting OPSCTL_LOGS_TOP=2, the command line --top 4 has no effect” — Lesson 3's convention is command-line options take precedence: the result is 4; only with -v do you see a DEBUG line. flag value '4' overrides OPSCTL_LOGS_TOP=2. Environment variables take effect only when there is no corresponding option.
bin/opsctlsource log/util/config · config::init load_command logssource lib/cmd_logs.sh cmd::logs → logs::reportset_flag / config::get usage_error → 2die (unreadable) → 1require_cmd → 3 LC_ALL=C awk -v top -v format -f lib/logs_report.awkPer line: validate $9 → hits[path]++ status[$9]++ bytes+=$10 err5[path]++END: printf the report; for-in | "sort" then close() FILE / - / default<data_dir>/access.log stdout: text / tsv report stderr: log::* / awk errors ~/bashlab/opsctl/{bin/opsctl, lib/log.sh, lib/util.sh, lib/config.sh (+2 default keys), lib/cmd_logs.sh, lib/logs_report.awk}
Figure 8-1: files and control flow involved in one opsctl logs report invocation (the entry script needs no changes).
hits[path]/api/orders → 211/healthz → 121/ → 75 · /login → 74/api/orders/1042 → 67/static/app.js → 63 status[code]200 → 450 · 201 → 54301 → 12 · 302 → 19304 → 22 · 400 → 11401 → 6 · 404 → 9500 → 12 · 502 → 4 · 503 → 12 err5[path]/api/orders → 28keys not seen: err5[k]+0→ prints 0 instead of an empty string Scalartotal = 611bytes = 2703396bad (skipped) = 0e5 = 28 → 4.58%
Figure 8-2 awk's in-memory data structures after processing access.log (actual output): all 28 5xx errors occurred on /api/orders

One opsctl logs report run's execution

Select a scenario and step through the real control flow: which function is running, what checks it performs, which processes it starts (fork/exec), and the final output and exit code.

Call stack / processes
stdout / stderr / exit code
Ready.
$

Complete implementation (3 changes)

Work on top of Lesson 4's final opsctl v0.2.0 (~/bashlab/opsctl) as the starting point. bin/opsctl No changes needed: it auto-discovers lib/cmd_logs.sh; strict mode, the ERR/EXIT trap and EX_* constants are provided by v0.2's entry point and lib/util.sh .

① lib/config.sh: register two new keys in OPSCTL_DEFAULTS

declare -gA OPSCTL_DEFAULTS=(
  [env]=dev
  [data_dir]="$HOME/bashlab/data"
  [log_level]=info
  [output]=table
  [logs_top]=5          # Lesson 5: number of paths logs report shows by default
  [logs_format]=text    # Lesson 5: text | tsv
)

Simply add these two lines with an editor (OPSCTL_DEFAULTS this is also the allowlist of config-file keys: afterwards etc/opsctl.conf , writing logs_top = 10 will also be accepted). Verify: grep -n 'logs_' lib/config.sh.

② lib/cmd_logs.sh: subcommand

cd ~/bashlab/opsctl
cat > lib/cmd_logs.sh <<'OPSCTL_EOF'
# shellcheck shell=bash
# opsctl-summary: summarize an access log (logs report [--top N] [--format text|tsv] [FILE|-])
# lib/cmd_logs.sh —— subcommand logs (added in Lesson 5, based on opsctl v0.2.0): the awk program lives in lib/logs_report.awk

logs::usage() {
  cat <<EOF
Usage: ${OPSCTL_PROG:-opsctl} logs report [options] [FILE|-]
Summarize a combined-format access log: requests, status codes,
top paths and 5xx error rate. FILE defaults to <data_dir>/access.log;
'-' reads standard input (e.g. zcat access.log.1.gz | opsctl logs report -).
Options:
  -n, --top N          number of paths to show   (default: logs_top = 5)
  -f, --format FMT     text | tsv                (default: logs_format = text)
  -h, --help           show this help
Environment: OPSCTL_LOGS_TOP, OPSCTL_LOGS_FORMAT, OPSCTL_DATA_DIR.
EOF
}

cmd::logs() {
  local action=${1-}
  case $action in
    report)         shift; logs::report "$@" ;;
    -h|--help|help) logs::usage ;;
    "")             logs::usage >&2; return 2 ;;
    *)              util::usage_error "unknown logs action: '$action'" ;;
  esac
}

logs::report() {
  local top format data_dir file src
  while (( $# )); do
    case $1 in
      -n|--top|-f|--format)
        [[ $# -ge 2 && -n $2 ]] || util::usage_error "option '$1' requires an argument"
        case $1 in
          -n|--top)    config::set_flag logs_top "$2" ;;
          -f|--format) config::set_flag logs_format "$2" ;;
        esac
        shift 2 ;;
      --top=*)    config::set_flag logs_top "${1#*=}"; shift ;;
      --format=*) config::set_flag logs_format "${1#*=}"; shift ;;
      -h|--help)  logs::usage; return 0 ;;
      --)         shift; break ;;
      -?*)        util::usage_error "unknown option for 'logs report': $1" ;;
      *)          break ;;   # FILE or "-"
    esac
  done
  (( $# <= 1 )) || util::usage_error "unexpected argument: $2"

  config::get logs_top top src || return 1
  [[ $top =~ ^[1-9][0-9]*$ ]] \
    || util::usage_error "invalid top '$top' (from $src); expected a positive integer"
  config::get logs_format format src || return 1
  util::in_list "$format" text tsv \
    || util::usage_error "invalid format '$format' (from $src); expected text|tsv"
  if (( $# == 1 )); then
    file=$1
  else
    config::get data_dir data_dir || return 1
    file=$data_dir/access.log
  fi
  [[ $file == - || ( -r $file && ! -d $file ) ]] || util::die "cannot read log file: $file" "$EX_ERR"
  util::require_cmd awk sort head

  log::debug "logs report: file=$file top=$top format=$format"
  # LC_ALL=C: byte semantics, deterministic sorting, faster; the sort started by awk inherits it
  # placed on the right of ||: set -e and the ERR trap do not interfere; the case below gives a clear error based on awk's exit code
  local rc=0
  LC_ALL=C awk -v top="$top" -v format="$format" \
    -f "$OPSCTL_HOME/lib/logs_report.awk" -- "$file" || rc=$?
  case $rc in
    0)   ;;
    1)   util::die "no valid log lines in $file (expected combined log format)" "$EX_ERR" ;;
    141) return 141 ;;   # SIGPIPE: downstream closed the pipe early (e.g. | head), not an error
    *)   util::die "awk failed (exit $rc) while reading $file" "$EX_ERR" ;;
  esac
}
OPSCTL_EOF

# Why not let awk's exit code bubble up directly? v0.2's ERR trap would treat it as an “unexpected failure” and print a call stack (at runtime you would see command failed (exit 1): LC_ALL=C awk … adding 4 lines of at …). “No valid lines in the log” is an expected business error and should produce one clear ERROR line. ! -d Prevents treating a directory as a log (awk would only warn and skip it, so the result becomes “no valid lines”).

③ lib/logs_report.awk: single-pass report program

cat > lib/logs_report.awk <<'OPSCTL_EOF'
# logs_report.awk —— POSIX awk (gawk / mawk / BWK awk all work)
# Input: combined format  $1=IP $4=[time $6="method $7=path $8=protocol" $9=status $10=bytes
$9 !~ /^[1-5][0-9][0-9]$/ { bad++; next }        # not a valid status code → skip and count
{
  total++
  path = $7; sub(/\?.*/, "", path)                # strip query string ?page=2
  hits[path]++
  status[$9]++
  klass[substr($9, 1, 1) "xx"]++
  if ($9 >= 500) { e5++; err5[path]++ }
  if ($10 ~ /^[0-9]+$/) bytes += $10              # "-" is not counted
}
END {
  if (total == 0) exit 1                         # no valid lines → exit code 1, reported by cmd_logs.sh
  rate = e5 / total
  if (format == "tsv") {
    print "metric\tkey\tvalue"
    printf "total\t-\t%d\n", total
    for (s in status) printf "status\t%s\t%d\n", s, status[s] | "sort"
    close("sort")
    for (k in hits) printf "path\t%s\t%d\n", k, hits[k] | "sort"
    close("sort")
    printf "error_rate_5xx\t-\t%.4f\n", rate
    exit 0
  }
  printf "== access log report ==\n"
  printf "requests: %d  bytes: %d  skipped: %d\n", total, bytes, bad
  print "\n-- status codes --"
  for (s in status) printf "%s %6d  %5.1f%%\n", s, status[s], 100 * status[s] / total | "sort"
  close("sort")
  printf "\n-- top %d paths --\n", top
  cmd = "sort -k1,1nr -k2,2 | head -n " top
  for (k in hits) printf "%6d  %-16s 5xx=%d\n", hits[k], k, err5[k] + 0 | cmd
  close(cmd)
  printf "\n5xx error rate: %.2f%% (%d/%d)\n", 100 * rate, e5, total
}
OPSCTL_EOF
bin/opsctl help | grep logs
bin/opsctl logs report; echo "rc=$?"          # no FILE given: uses <data_dir>/access.log
  logs             summarize an access log (logs report [--top N] [--format text|tsv] [FILE|-])
== access log report ==
requests: 611  bytes: 2703396  skipped: 0

-- status codes --
200    450   73.6%
201     54    8.8%
301     12    2.0%
302     19    3.1%
304     22    3.6%
400     11    1.8%
401      6    1.0%
404      9    1.5%
500     12    2.0%
502      4    0.7%
503     12    2.0%

-- top 5 paths --
   211  /api/orders      5xx=28
   121  /healthz         5xx=0
    75  /                5xx=0
    74  /login           5xx=0
    67  /api/orders/1042 5xx=0

5xx error rate: 4.58% (28/611)
rc=0

klass (2xx/3xx…) are not used in the output; left for you to extend in the lab. printf "%d", bad When bad is unassigned, it prints 0 (uninitialized variables are 0 in numeric context).

# Machine-readable output
bin/opsctl logs report --top 3 --format tsv ~/bashlab/data/access.log

# Error paths and exit codes (log format from v0.2's lib/log.sh: time level program[PID]: message)
bin/opsctl logs report --top x; echo "rc=$?"
bin/opsctl logs report nofile; echo "rc=$?"
: > /tmp/empty.log; bin/opsctl logs report /tmp/empty.log; echo "rc=$?"
bin/opsctl logs frob; echo "rc=$?"

# stdin + bad lines
{ cat ~/bashlab/data/access.log; echo 'garbage line'; } | bin/opsctl logs report -n 2 - | sed -n '2p;/top 2/,$p'
# Precedence: command-line options > environment variables; with -v you see a DEBUG line
OPSCTL_LOGS_TOP=2 bin/opsctl logs report --top 4 | sed -n '/top/,/^$/p'
OPSCTL_LOGS_TOP=2 bin/opsctl -v logs report --top 4 2>&1 >/dev/null | grep overrides
metric	key	value
total	-	611
status	200	450
status	201	54
status	301	12
status	302	19
status	304	22
status	400	11
status	401	6
status	404	9
status	500	12
status	502	4
status	503	12
path	/	75
path	/api/orders	211
path	/api/orders/1042	67
path	/healthz	121
path	/login	74
path	/static/app.js	63
error_rate_5xx	-	0.0458
2026-11-17T09:36:32-0500 ERROR opsctl[136]: invalid top 'x' (from flag); expected a positive integer
Try 'opsctl --help' for more information.
rc=2
2026-11-17T09:36:32-0500 ERROR opsctl[140]: cannot read log file: nofile
rc=1
2026-11-17T09:37:55-0500 ERROR opsctl[285]: no valid log lines in /tmp/empty.log (expected combined log format)
rc=1
2026-11-17T09:36:32-0500 ERROR opsctl[148]: unknown logs action: 'frob'
Try 'opsctl --help' for more information.
rc=2
requests: 611  bytes: 2703396  skipped: 1
-- top 2 paths --
   211  /api/orders      5xx=28
   121  /healthz         5xx=0

5xx error rate: 4.58% (28/611)
-- top 4 paths --
   211  /api/orders      5xx=28
   121  /healthz         5xx=0
    75  /                5xx=0
    74  /login           5xx=0

2026-11-17T09:39:03-0500 DEBUG opsctl[1651]: flag value '4' overrides OPSCTL_LOGS_TOP=2

In TSV mode, --top has no effect (all paths are output); filter downstream as needed. Timestamps, time zone and PID are the actual values from the authoring environment; yours will differ. --top 4 overrides OPSCTL_LOGS_TOP=2, and in default (non- -v) runs, there is no hint at all on stderr.

# Combined usage
zcat /var/log/nginx/access.log.*.gz | bin/opsctl logs report --top 10 -
# Threshold check: exit 1 when exceeded, for cron / CI
th=0.04
bin/opsctl logs report --format tsv |
  awk -F'\t' -v th="$th" '$1=="error_rate_5xx" { printf "rate=%s threshold=%s\n", $3, th; exit ($3 > th) }' \
  || echo "5xx error rate above threshold"
rate=0.0458 threshold=0.04
5xx error rate above threshold
How to verify / Common errors / Production use Verify: independently compute with grep (grep -cE '" 5[0-9]{2} ' should be 28); bin/opsctl -v logs report print debug logs (dispatch and arguments); gawk --posix -v top=5 -v format=text -f lib/logs_report.awk ~/bashlab/data/access.log >/dev/null (confirm only POSIX features are used; --lint will warn a lot about the awk idiom “uninitialized variables are 0”). Common errors: forgetting close() causes out-of-order output; forgetting to OPSCTL_DEFAULTS register the new key → config::get: unknown key 'logs_top'; --top unvalidated values spliced into head -n (validate with a regex first here to prevent command injection). Production use: the first step in the on-call runbook, cron appending TSV to the report hourly, and automatic before/after error-rate comparison after a release.

Lab 8: implement, run and extend opsctl logs report

Goal: Complete the subcommand and add one new feature. Environment:~/bashlab/opsctl (v0.2.0) + make-data.sh data. Cleanup: No cleanup needed (the results are kept for Lessons 6 and 7).

Make three changes: edit the “Commands” tabs in lib/config.sh, create lib/cmd_logs.sh and lib/logs_report.awk; confirm bin/opsctl help appears in logs.
Run and verify independently
cd ~/bashlab
opsctl/bin/opsctl logs report | tail -1
LC_ALL=C grep -cE '" 5[0-9]{2} ' data/access.log; wc -l < data/access.log
5xx error rate: 4.58% (28/611)
28
611
Run on both mawk and gawk (portability)
for a in mawk gawk; do
  command -v "$a" >/dev/null || continue
  mkdir -p /tmp/awkbin && ln -sf "$(command -v "$a")" /tmp/awkbin/awk
  PATH=/tmp/awkbin:$PATH opsctl/bin/opsctl logs report | md5sum
done

The two md5 values should match (output order is determined by sort, independent of the awk implementation).

Experience config precedence
echo 'logs_top = 3' >> opsctl/etc/opsctl.conf
opsctl/bin/opsctl logs report | grep -c '5xx='              # 3 (from config file)
opsctl/bin/opsctl logs report --top 6 | grep -c '5xx='      # 6 (flag overrides file)
OPSCTL_LOGS_TOP=1 opsctl/bin/opsctl logs report | grep -c '5xx='            # 1 (env overrides file)
OPSCTL_LOGS_TOP=1 opsctl/bin/opsctl logs report --top 6 | grep -c '5xx='    # 6 (flag has highest priority)
sed -i.bak '/^logs_top = 3$/d' opsctl/etc/opsctl.conf && rm opsctl/etc/opsctl.conf.bak
Extension: add --max-5xx RATE: when the threshold is exceeded the report is still printed, but it exits with code 4 so cron / CI can judge. Reference snippet (also in OPSCTL_DEFAULTS add [logs_max_5xx]=1):
# In the case of logs::report:
      --max-5xx) [[ $# -ge 2 ]] || util::usage_error "option '$1' requires an argument"
                 config::set_flag logs_max_5xx "$2"; shift 2 ;;
# Value and validation:
  config::get logs_max_5xx max5xx src || return 1
  [[ $max5xx =~ ^(0(\.[0-9]+)?|1(\.0+)?)$ ]] || util::usage_error "invalid max-5xx '$max5xx' (from $src)"
# Add to the awk call: -v max5xx="$max5xx"
# Add at the end of END (don't use 1 — it already means “no valid lines”): if (rate > max5xx) exit 4
# Add to the case in cmd_logs.sh: 4) log::warn "5xx rate above $max5xx"; return "$EX_ERR" ;;
Prepare test samples for Lesson 7
mkdir -p opsctl/test/fixtures
cp data/access.log opsctl/test/fixtures/access.sample.log
opsctl/bin/opsctl logs report --format tsv opsctl/test/fixtures/access.sample.log > opsctl/test/fixtures/report.expected.tsv
# The Lesson 7 bats tests assert: run opsctl logs report --format tsv … ; [ "$output" = "$(cat expected)" ]

Acceptance

Case 1: automatic comparison after a release

Problem: After each release, a person checks Grafana by hand to decide whether to roll back; night releases often get delayed. Fix: the release script (Lesson 6) waits 5 minutes after the switch, then uses journalctl / nginx logs to slice 5 minutes before and after the switch, and runs opsctl logs report --format tsv, then compares error_rate_5xx; if the threshold is exceeded, roll back automatically. Limitations: At low traffic, ratios are noisy, so a minimum request count must also be set.

Case 2: logs too large for awk to handle?

Symptom: a single machine with 20 GB of logs; the report takes several minutes. Fix: First, confirm the bottleneck: time zcat … >/dev/null (decompression is often the bottleneck; you can switch to pigz -dc); LC_ALL=C; mawk is usually faster than gawk; parallelize by file xargs -P Emit TSV first, then merge the counts with awk. Limits: At this scale, ship the logs to a centralized platform; use the shell only for emergencies.

Case 3: the log format changed silently

Symptom: In a recent nginx config change, $status had $request_time prepended; the report showed requests: 0 skipped: 120000 and exited with 1. Conclusion: This is exactly the value of validation plus a skipped count plus a non-zero exit code: the format change is caught immediately instead of quietly producing a wrong error rate. Fix: put the log format in the config (make the field positions configurable), or have nginx emit JSON logs.

Interactive troubleshooting tree: opsctl logs report gives wrong results or fails

ERROR opsctl[…]: no valid log lines in … (expected combined log format) (rc=1)

Cause: The file is empty, or the format is not combined (column 9 is not a 3-digit status code). Diagnosis:head -3 file | awk '{print NF": "$9}'. Fix: Confirm the log format; for JSON logs, use jq (module 6).

In the output, “-- status codes --” ends up at the end of the report

Cause: In awk, after writing to "sort" without calling close("sort"), sort only produces output when awk exits. Fix: Immediately after using each pipe, call close(), and the command string used in close() must be exactly the same as when it was opened.

awk: cannot open lib/logs_report.awk (No such file or directory)

Cause: It used a relative path, so opsctl cannot be found when called from another directory. Fix: Use $OPSCTL_HOME/lib/logs_report.awk (the entry script computes it from BASH_SOURCE ).

ERROR opsctl: unknown command: logs (rc=2)

Cause:opsctl::load_command Cannot find lib/cmd_logs.sh (wrong file name, extension, or directory), or the file does not define cmd::logs (declare -F failed). Diagnosis:ls opsctl/lib/cmd_*.sh; bash -c 'source opsctl/lib/cmd_logs.sh; declare -F cmd::logs'. Fix: Confirm the file location and the function name; opsctl help shows logs, which means the summary comment was also read.

ERROR opsctl: config::get: unknown key 'logs_top'

Cause: Forgot to add the new key in lib/config.sh 's OPSCTL_DEFAULTS whitelist. config::get Keys not on the whitelist return 1, and a config-file entry such as logs_top = … is also ignored as an unknown key. Fix: Add [logs_top]=5 and [logs_format]=text.

Command questions

1. Using opsctl's TSV output, print only the 5xx error rate (as a percentage, rounded to 1 decimal place).
opsctl/bin/opsctl logs report --format tsv data/access.log | awk -F'\t' '$1=="error_rate_5xx" { printf "%.1f%%\n", $3 * 100 }'
# 4.6%
2. Generate one combined report for all rotated logs (including .gz) under /var/log/nginx.
find /var/log/nginx -name 'access.log*' -print0 | sort -z |
  xargs -0 zcat -f -- | opsctl/bin/opsctl logs report --top 10 -
# zcat -f: pass uncompressed files through unchanged

Scenario analysis questions

A colleague proposes changing the report to grep -c ' 500 ' | … a chain of grep pipelines like this, which is “easier to understand”. Evaluate it for correctness, performance and maintainability.

Correctness: grep does not understand columns,' 500 ' so it can match content in the UA or Referer, and it cannot tell 500 from a byte count (module 1 case); awk validates by column and counts skipped lines. Performance: several greps mean scanning the file several times, while awk gets every metric in a single pass. Maintainability: multiple pipelines are spread across the shell, with more quoting and escaping; a commented .awk file can be tested and linted separately. Conclusion: keep the awk implementation, and use comments plus the lesson 7 tests to keep it readable.

Verified instructional videos

▶
How The 'awk' Command Made Me A 10x Engineer — RobertElderSoftware
English · how to process real data with awk, matching this module's report program
▶
Bash in 100 Seconds — Fireship
English · about 2 minutes · review the overall structure of a Bash script

Official documentation

Video storyboard script (about 90 seconds)

This courseware cannot generate a video or MP3 directly. The storyboard and narration script are provided and can be handed to a video tool.

Shot 1 · 0–20s
Visual: the on-duty terminal runs opsctl logs report access.log, the report appears instantly, and the 5xx error rate flashes at 15 percentage points.
Narration: at the incident scene, the first thing is to know how many errors there are and which path they cluster on.
Shot 2 · 20–50s
Visual: the call stack unfolds layer by layer: the opsctl entry point, cmd::logs, logs::report, argument validation, then awk starts.
Narration: subcommands follow a common convention: bad arguments exit with code 2, unreadable files with 1, missing dependencies with 3.
Shot 3 · 50–75s
Visual: awk scans once while four hash tables grow at the same time; in END, three sort pipes open and close one after another.
Narration: one scan computes all the metrics, and close ensures the sorted results are printed in order.
Shot 4 · 75–90s
Visual: TSV output flows into an awk threshold check; when the threshold is exceeded, a red light comes on and triggers a rollback.
Narration: text for people to read, TSV for machines to read: the same data, two uses.
or score ≥ 70% on the “Quiz”

Command cheat sheet

Text and data processing: a one-page reference covering all the common patterns in this lesson
Print-friendlyIn scripts, first export LC_ALL=C

grep

grep -E 'a|b(c)?' f       # ERE
grep -F 'a.b?c' f         # fixed string
grep -P '\d+\K\w+' f      # PCRE (GNU only)
grep -o / -c / -n / -w / -v / -q / -m N
grep -rn --include='*.sh' 'TODO' dir
grep -rlZ pat dir | xargs -0 cmd
grep -e '-v' f            # pattern starts with -
# exit status: 0 found · 1 not found · 2 error

sed

sed -E 's/(re)/[\1]/g' f
sed -n '10,20p' f ; sed -n '$p' f ; sed '20q' f
sed -n '/START/,/END/p' f
sed '/^#/d; /^$/d' f
sed 's|/old|/new|g' f     # change the delimiter
sed 's/\r$//' f           # CRLF → LF
sed -i.bak 's/a/b/' f && rm f.bak   # works on GNU and BSD
sed --debug '…' f         # GNU

awk

awk -F, -v OFS='\t' 'NR>1 {print $1,$4}' f
awk '$9>=500' access.log
awk '{c[$9]++} END{for(k in c) print k,c[k]}' f | sort
awk '!seen[$0]++' f       # dedupe, keep order
awk 'NR==FNR{a[$1];next} $1 in a' keys f
awk '{s+=$10} END{print s, s/NR}' f
awk -v x="$v" … ; ENVIRON["V"]   # pass arguments
print … | "sort"; close("sort")
gawk --csv '…' f.csv      # gawk ≥ 5.3

find / xargs

find . -type f -name '*.log' -mtime +7 -print
find . -path ./.git -prune -o -type f -print
find . -type f -exec cmd -- {} +
find . -type f -print0 | xargs -0 -r -P4 -n50 cmd --
while IFS= read -r -d '' f; do …; done < <(find . -print0)
find . -name '*.tmp' -delete     # put -delete last
rm -- "$f" ; rm ./*              # guard against a leading -
# xargs exit status: 123 a sub-command failed · 127 command not found

sort / uniq / comm / join / cut / paste

sort -t, -k2,2 -k1,1nr f
sort | uniq -c | sort -k1,1nr -k2
sort -V ; sort -h ; sort -u ; sort -c
comm -23 <(sort a) <(sort b)     # only in a
comm -12 …                       # intersection
join -t, -a1 -e NONE -o 0,1.2,2.2 a b
cut -d, -f1,4 f ; cut -c1-15 f
paste -sd, - ; paste - - ; paste -d, a b

jq / yq

jq -r '.[] | select(.env=="prod") | .name' f
jq -r --arg e "$e" '.[] | select(.env==$e)' f
jq -r '.[] | [.a,.b] | @tsv' f
jq -c 'group_by(.k) | map({k:.[0].k, n:length})' f
jq -e '…' f >/dev/null && echo yes
jq --raw-output0 '.[].name' f | xargs -0 …   # jq ≥ 1.7
yq '.a.b' f.yaml ; yq -o=json f.yaml
V=x yq -i '.a.b = strenv(V)' f.yaml
yq -p=csv -o=json f.csv

CSV

awk -F, '{print NF}' f | sort | uniq -c   # check column counts
gawk --csv '{print $5}' f.csv
mlr --icsv --opprint filter '$env=="prod"' f.csv
mlr --icsv --ojson cat f.csv
python3 -c 'import csv,sys; [print(r["name"]) for r in csv.DictReader(open(sys.argv[1],newline=""))]' f.csv
sed '1s/^\xEF\xBB\xBF//; s/\r$//' f.csv   # strip BOM/CRLF

opsctl logs

opsctl logs report data/access.log
opsctl logs report --top 10 --format tsv f
zcat f.gz | opsctl logs report -
# exit status: 0 success · 1 error / no valid lines · 2 usage · 3 missing dependency

Quick troubleshooting table

Symptom / errorMost likely causeFix
stray \ before dIn BRE/ERE, used \d[0-9] or grep -P
invalid option -- P / sed: 1: … invalid command codemacOS / BusyBox toolsUse POSIX syntax,-i.bak, or install the GNU version
function gensub never definedawk is mawkUse POSIX functions or explicitly gawk
Report row order changes between runsfor (k in a) Unordered / ties with no defined secondary key| "sort" + close(); -k1,1nr -k2
xargs: unmatched single quoteFile name contains quotes-print0 | xargs -0
Argument list too longExceeds ARG_MAXfind -exec {} + / xargs
comm: file 1 is not in sorted orderLocale mismatch / unsorted inputall of them LC_ALL=C
CSV columns shiftCommas inside quotesgawk --csv / mlr / Python
parse error: Invalid numeric literalInput is not JSONCheck the upstream output,-o json,curl -f
yq does not understand the syntax at allinstalled the Python version of yqInstall mikefarah v4

Recommended script header (for text-processing scripts)

#!/usr/bin/env bash
set -Eeuo pipefail
export LC_ALL=C                 # deterministic sort and byte semantics; switch to C.UTF-8 when processing Chinese text
util::require_cmd awk sort jq   # missing dependency → exit code 3
# only use POSIX grep -E/-F, sed -E and awk; when you need gawk/GNU features, call them explicitly and check for them

Integrated lab + final quiz

“Incident review data pack”: use all the tools from this lesson to answer 6 operations questions from logs, inventory, configuration and files
About 25 minutesLocal · no cost
Scenario: between 10:00–10:31 /api/orders 5xx has been appearing intermittently. Your on-duty colleague gave you a directory (that is ~/bashlab/data): access logs, a host inventory (CSV and JSON), sample configuration, and a folder collected from servers (with messy file names). Without modifying the original data, produce a post-incident review report /tmp/postmortem.md.
Set up the workspace and report header, and record a fingerprint of the original data
cd ~/bashlab && export LC_ALL=C
out=/tmp/postmortem.md
cksum data/access.log data/servers.csv data/inventory.json > /tmp/before.cksum
{ echo "# Review data: 2026-11-17 10:00–10:31 UTC"; echo; } > "$out"
Question 1: overall picture (opsctl logs report)
{ echo '## 1. Overall'; echo '```'; opsctl/bin/opsctl logs report data/access.log; echo '```'; } >> "$out"

Conclusion: 611 requests, 28 5xx responses (4.58%),all of them occurred in /api/orders (5xx=28).

Question 2: time window and sources of the 5xx errors (awk)
{
  echo '## 2. 5xx time window and sources'
  awk '$9 >= 500 { if (!f) f = substr($4, 14, 8); l = substr($4, 14, 8) } END { print "Window: " f " – " l }' data/access.log
  awk '$9 >= 500 { c[$1]++ } END { for (ip in c) print c[ip], ip }' data/access.log | sort -k1,1nr -k2 | head -3
} >> "$out"
## 2. 5xx time window and sources
Window: 10:02:08 – 10:28:39
7 10.20.1.31
4 10.10.1.22
4 192.0.2.12
Question 3: who is 10.20.1.31, and what were its request results? (awk associative array + sorted counts)
{ echo '## 3. 10.20.1.31'
  awk -F, -v ip=10.20.1.31 '$4 == ip { print "Inventory: " $1 "@" $2 " (" $5 ")" }' data/servers.csv
  awk '$1 == "10.20.1.31" && $9 >= 500 { print NR, substr($4, 14, 8), $9 }' data/access.log; } >> "$out"
## 3. 10.20.1.31
Inventory: web-01@staging (web)
136 10:07:18 503
317 10:15:46 500
458 10:22:58 502
459 10:22:59 502
460 10:23:00 502
461 10:23:01 502
479 10:23:57 500

The “client” is actually web-01 in staging: starting at 10:22:58 it received 502 four times in a row (lines 458–461). This is an upstream gateway-level problem, not user traffic. In the review, ask why staging is calling this environment's API.

Question 4: which prod hosts have the api role, and what is the prod health check address? (jq + yq)
{ echo '## 4. prod api hosts and health check'
  jq -r '.[] | select(.env == "prod" and (.role | split(",") | index("api"))) | "\(.name)\t\(.ip)"' data/inventory.json
  echo "health_url: $(yq '.environments.prod.health_url' data/config.yaml)"; } >> "$out"
## 4. prod api hosts and health check
api-01	10.30.1.43
edge-01	10.30.2.51
health_url: https://shop.example.com/healthz

edge-01 's role is "web,api": use split(",") | index("api") by list membership, not .role == "api" (which would miss it) or test("api") (which would falsely match things like "rapid" ).

Question 5: are the CSV and JSON inventories consistent? (Python csv + jq + comm)
{ echo '## 5. Inventory consistency'
  comm -3 \
    <(python3 -c 'import csv,sys; [print(r["name"]+"@"+r["env"]+","+r["role"]) for r in csv.DictReader(open(sys.argv[1],newline=""))]' data/servers.csv | sort) \
    <(jq -r '.[] | .name + "@" + .env + "," + .role' data/inventory.json | sort)
  echo "(no output = consistent)"; } >> "$out"
Question 6: list of collected files (safe file name handling)
{ echo '## 6. Collected files'
  find data/files -type f -print0 | sort -z | xargs -0 -r ls -ld -- | awk '{ $1=$2=$3=$4=""; sub(/^ +/, ""); print }'
  printf 'Total %d files\n' "$(find data/files -type f -printf . | wc -c)"; } >> "$out"
cksum data/access.log data/servers.csv data/inventory.json | diff /tmp/before.cksum - && echo "Original data unchanged"
cat "$out"

Note: ls -l Output with newline-containing file names still shows them on two lines. For a list meant for people to read, use find … -printf '%s\t%p\n' together with printf '%q' is clearer. The main point here is that passing file names is safe at every step.

(Optional) Write the whole process as a script ~/bashlab/postmortem.sh, start it with the “recommended script header” from the cheat sheet, and check it with ShellCheck (covered in detail in lesson 7).

Acceptance checklist

Open-ended self-check (answer first, then expand)

1. You want to count 5xx responses per upstream (upstream_addr, which comes after the UA) in the nginx log. Why is awk's default FS unreliable? What are the alternatives?

The UA contains spaces, so the positions of the fields after it shift from line to line. Options: use $NF (if upstream is the last field and has no spaces); gawk match() with a specific pattern; change log_format to put upstream before the UA, or use TSV/JSON output (escape=json) and then use jq.

2. Why is it said that LC_ALL=C for sort/comm/join is a “correctness problem”, not just a “performance problem”?

The sort order defines what “sorted” means. Running sort and comm/join under different collations leads to “not sorted” errors or silently wrong results. Results can also differ between machines (cron versus interactive sessions, Ubuntu 26.04's uutils versus GNU). The C locale gives a deterministic, byte-based order that does not depend on the environment.

3. When should you stick with sed to edit a config file, and when must you use yq?

Plain-text, line-oriented configuration (e.g. KEY=VALUE 's env file, and single-line sshd_config directives) can be edited with sed (anchor to the line start, preview the diff, keep a backup); structured files such as YAML/JSON, or files with duplicate or nested keys, should be edited by path with yq/jq; configuration across many hosts should go to a configuration management tool such as Ansible.

4. Compare the use cases of find -exec … {} +,xargs -0, and while read -d '' .

-exec +: the simplest option, POSIX, no pipe needed; good for running the same command on a batch of files; xargs -0: when you need parallelism (-P), or when the input comes from another command that emits NUL-separated output; while read -d '': each file needs Bash logic (computing a new name, conditionals, accumulating variables); use process substitution rather than a pipe so the variables are preserved.

5. Why does opsctl's report put its awk program in a separate file? What are the costs?

Benefits: it avoids nested single quotes in the shell, it can be linted and tested on its own, and ShellCheck will not give false positives on awk's $1 false positives. Costs: one more file to ship with the script, which must be located via $OPSCTL_HOME , and it must be copied along during installation or packaging (the release process in lesson 7 handles this).

6. Which signals would make you rewrite a shell data-processing script in Python?

You need to parse complex formats beyond CSV/JSON correctly; you need typed values, date and timezone calculations; you need unit tests covering many branches; the script grows past a hundred or two lines or nests several layers of awk/sed; you need concurrent API access with retries; or the team maintaining it knows Python better. The shell keeps its role as “glue”: calling these programs and handling their exit codes.

Final quiz

Sources and version notes

Verified 2026-11-17. All output labeled “Actual output” was produced on this machine with Bash 5.2 and GNU tools, running against the dataset generated by lesson 1's make-data.sh (cksum verified)
Verified 2026-11-17
TopicVerified findingSource (accessed 2026-11-17)
Rust coreutils in Ubuntu 26.0426.04 includes rust-coreutils (uutils) 0.8.0; cp/mv/rm Still GNU for now because of an unresolved TOCTOU issue; can be switched via coreutils-from-gnu / coreutils-from-uutils a package switch (announcement 2026-04-22)Ubuntu Discourse
sort/comm incompatibility reportsLaunchpad #2152822 (2026-05): LC_COLLATE=en_US.UTF-8 with it, comm reports “file 1 is not in sorted order”; another report says sort -k behaves differently from GNU.Launchpad
Ubuntu 26.04 package versionsgrep 3.12, sed 4.9, findutils 4.10.0, gawk 5.3.2, mawk 1.3.4-20260129, jq 1.8.1, miller 6.16.0,yq package 3.4.3 (kislyuk's Python version)Launchpad (resolute) · packages.ubuntu.com
Ubuntu default awkNo explicit official statement was found; Launchpad material shows that the minimal image uses mawk, and if gawk is installed, its alternatives priority is higher. This lesson recommends using readlink -f /etc/alternatives/awk to confirm (the conservative approach)Launchpad #1841654
GNU grepSince 3.8 (2022-09), egrep/fgrep prints a deprecation warning,-P switches to PCRE2, and stray backslashes trigger a warningGNU grep manual · grep 3.8 release announcement
gawk --csvgawk 5.3 added a CSV mode; on this machine, gawk 5.3.2 handles quoted commas,"" and newlines inside fieldsgawk manual
POSIX.1-2024find -print0 and xargs -0 have been incorporated into the standardxargs · find
jqThe latest upstream release is 1.8.2 (2026-06); 1.8.0 introduced trim/ltrim/rtrim,limit an error for negative numbers,ltrimstr an error for non-string values, and similar changes; --raw-output0 since 1.7jq Releases · jq Manual
yq (mikefarah)Latest v4.54.3 (2026-11-09); install via Release binary / snap / brew; usage yq '.a.b' f,yq -i,strenv(),-o json; the README notes that the Debian package is no longer maintainedGitHub · Releases
MillerLatest upstream is 6.22.0 (2026-09-25); Ubuntu 26.04 has 6.16.0Miller Releases
Data and opsctl interface for this lessonThe dataset is generated by lesson 1's make-data.sh (611 access-log lines, 12 hosts, 15 files with unusual names); this lesson is based on opsctl v0.2.0 (lesson 3 integrated lab v0.1 + lesson 4 v0.2 upgrade: strict mode + inherit_errexit, setup_traps, EX_* constants); configuration precedence: command-line options > environment variables > configuration file > defaultsLesson 1 setup page · Lesson 3 integrated lab · Lesson 4
Docker image bash:5.3Official images exist on Docker Hub with tags such as 5.3,5.3.20 and so on (Alpine base, with BusyBox tools)Docker Hub: bash
CSV formatRFC 4180 (Informational)RFC Editor

Video verification notes

All videos were checked via YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json) on 2026-11-17 to verify titles and channels:

No verified English video was found that specifically covers -print0 | xargs -0, comm/join, jq/yq and CSV edge cases; the corresponding modules are noted accordingly and provide storyboard scripts. Duration and publication date were not obtained via oEmbed, so the text gives only rough descriptions.

Audio narration notes

The “Audio” tab uses the browser's built-in Web Speech API (speechSynthesis, reads the narration with a zh-CN voice, and uses an en-US voice for English terms). This courseware is a single offline file,cannot embed or generate MP3 files; numbers and version numbers in the narration have been written in a form suitable for reading aloud. For an audio file, give the narration script to any TTS tool.

Known limitations

  • Output labeled “Actual output” was produced on this machine (Git Bash on Windows: Bash 5.2.37, GNU grep 3.0, GNU sed 4.9, gawk 5.3.2, findutils 4.10.0, sort from GNU coreutils 8.32, jq 1.6, Python 3.14) by running the make-data.sh dataset (access.log cksum 80306651 79109, matching lesson 1); the opsctl output is the code extracted from the lesson 3 integrated lab and the lesson 4 v0.2 steps (v0.2.0, strict mode), plus actual runs of this lesson's cmd_logs.sh; Ubuntu 26.04 (Bash 5.3, grep 3.12, uutils sort, jq 1.8) should give the same results, but this was not re-checked line by line on that system.
  • In the current locale, grep 3.0 on this machine does not support -P , so the output of grep -P is derived from PCRE2 semantics and labeled “example”; mikefarah yq and Miller were not run on this machine, so their output is labeled “example” (refer to the official README/documentation for syntax).
  • The inode numbers, timestamps and host names in the “Lab” are example values; cloud CLI (az/aws) commands were not run against a real subscription.
  • make-data.sh is deterministic: as long as the cksum matches, the statistics should match this lesson exactly; the timestamps in the log lines (as printed by opsctl's log::_emit output, which uses the local time zone) are example values.
  • This lesson is based on opsctl v0.2.0: the code was extracted from the lesson 3 integrated lab and the lesson 4 v0.2 upgrade steps, and was run in strict mode in the scratchpad (set -Eeuo pipefail + inherit_errexit + util::setup_traps) ran all logs report test cases; the authoring environment had no shellcheck or flock, so these two were not checked in this lesson (logs report does not use locking).
  • uutils coreutils is evolving quickly, so the differences mentioned in this lesson (locale ordering,-k whitespace handling) may already be fixed in later versions; please treat sort --version and the Launchpad status as authoritative.
  • No official, explicit statement was found on “Is Ubuntu's default awk mawk or gawk?”; this lesson only gives a method to check.