Lesson 7 of 14 · 15m
sed, awk, and jq for Structured Text
Why sed -i is a rewrite not an edit, awk for fields and aggregates, and jq -e as a real test on JSON.
sed -i s/enabled=false/enabled=true/ app.conf looks like an in-place edit. It isn't. GNU sed writes a new file and rename(2)s it over the old one — new inode, new object. Your inotify watcher sees a delete and a create, your hardlink points at the stale copy, and if app.conf was a symlink, the link is now a regular file severed from its target. That last one is the Kubernetes trap: ConfigMap and Secret volumes are symlink trees into an atomic ..data directory, and sed -i on a mounted key either fails on the read-only mount or severs the live-update link. The "edit a config line" staple has more machinery under it than it looks.
sed: stream edits, real costs
sed -i.bak 's/listen 80/listen 8080/' nginx.conf # keeps nginx.conf.bak
sed -n '50,80p' app.log # print lines 50-80, no edit
sed '/^#/d; /^$/d' config.ini # strip comments and blanks-iwith no suffix works on GNU sed but demands an argument on BSD/macOS:sed -i '' 's/.../.../'— the empty string is the backup suffix. Scripts that run on both need the argument form:sed -i.bak, which GNU and BSD both accept.- Because
-irewrites the file, it can also fail halfway —sed -ion a full filesystem leaves a truncated target. For anything a consumer reads concurrently, write-then-mvyourself (the atomic pattern from themktemplesson) instead of trusting the replacement. sed -n+pis grep-with-ranges;s///is substitution;/re/,/re2/is a range. Everything else — nested quoting, conditionals on the match — is where you should stop shelling and reach forawkor a real language.
awk: columns and conditions
awk '{print $2}' access.log # second whitespace column
awk -F: '$3 >= 1000 {print $1}' /etc/passwd # human users on a Debian box
awk '$9 == 404 {n++} END {print n}' access.log # count 404s ($9 = status in common log format)
awk -F'[=,]' '{s+=$4} END {print s/NR}' # average of a keyed fieldawk splits each line into $1..$NF on -F, evaluates pattern { action } per line, and gives you NR (line number), NF (field count), $NF (last field), and END for aggregation. awk '$0 ~ /regex/' is grep; awk '{print $NF}' is rev | cut | rev done right. When your grep | awk | sed | awk chain hits four stages, write the awk program once — awk -f report.awk — instead of a pipeline nobody can audit.
Rule of thumb: grep selects lines, sed rewrites lines, awk computes over fields. When the "text" has structure — JSON, YAML, CSV with quoted commas — none of them are the right tool.
jq: the structured-data answer
jq -r '.containers[].image' pod.json # raw strings, one per line
jq -e '.spec.replicas > 1' deploy.json # exit 0/1 — a real test
jq --arg ns "$NAMESPACE" '.metadata.namespace = $ns' deploy.jsonjq -remits raw text instead of JSON-quoted strings — what you want for variable capture:img=$(jq -r '.image' spec.json).jq -esets the exit status on the last output value —jq -e '.enabled'exits1onfalse, which is how you test JSON booleans underset -e. Without-e,jqprintsfalseand exits0, and yourifreads the string, not the status.--argpasses shell values as typed JSON data — no quoting hazards, no injection.--argjson n "$N"for numbers/arrays.jq -n '{key: $k}' --arg k "$v"builds JSON from argv — always compose with--arg, never"{\"key\": \"$v\"}"string-interpolation, which hands quoting bugs to the parser.
Real sources it tames: docker inspect, gh api, aws ... --output json, kubectl get -o json, curl | jq. curl -sf ... | jq -e is a complete health contract: -f makes curl fail on HTTP errors, -e makes jq fail on bad content.
Try this
docker inspect nginx | jq -r '.[0].State.Pid'
kubectl get deploy app -o json | jq -e '.spec.replicas >= 2'
sed -i.bak 's/^;*date.timezone.*/date.timezone = UTC/' /etc/php.iniPitfalls
sed -ichanges inode and ownership context — on a hardlinked file the other link keeps the old content; checkls -iif "my edit didn't take" is the symptom.grep pattern filevsgrep -q: the quiet flag exits on first match — right forif, wrong for output you then pipe.jqabsent on minimal images —apk add jq,apt install jq; on hosts where you can't install,python3 -c 'import json,sys; ...'is the dependency-free fallback.awkdefault field splitting collapses runs of whitespace and trims edges — different fromcut, which honors exact delimiter positions;awkis right for ragged logs,cut -d, -f3for strict columns.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Red Hat Called This Bug a 5.9. Two Weeks Later It Was a 9.8.
CVE-2026-98432 is a use-after-free in the IPv4 TCP handshake, reachable by anybody who can reach a listening port, sitting in the kernel since 4.4. Red Hat scored it 5.9 moderate and deferred the fix. Then 8.1. Then 9.8.
Self-Host OpenClaw: VPS Setup to Production (2026)
Self-host OpenClaw from zero to production. Server provisioning, SSH lockdown, Docker, reverse proxy, Fail2ban, performance tuning, and full backup strategy in one guide.
Self-Hosting Prometheus and Grafana: Infrastructure Monitoring That Actually Works
Build a production-grade monitoring stack with Prometheus and Grafana from scratch. Covers architecture, Docker Compose deployment, Node Exporter, alerting with Alertmanager, PromQL from basics to advanced, pre-built dashboards, and everything SudoSecurity uses to monitor its own infrastructure.
Zero Trust Everything: The Complete Guide to Self-Hosting Teleport for Secure Infrastructure Access
SudoSecurity runs Teleport internally for everything — admin panel access, secure database connections, Kubernetes, and zero-trust philosophy across our entire team. This is the complete technical guide to installing, configuring, and running your own self-hosted Teleport cluster from scratch.