Skip to content

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
  • -i with 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 -i rewrites the file, it can also fail halfway — sed -i on a full filesystem leaves a truncated target. For anything a consumer reads concurrently, write-then-mv yourself (the atomic pattern from the mktemp lesson) instead of trusting the replacement.
  • sed -n + p is 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 for awk or 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 field

awk 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.json
  • jq -r emits raw text instead of JSON-quoted strings — what you want for variable capture: img=$(jq -r '.image' spec.json).
  • jq -e sets the exit status on the last output value — jq -e '.enabled' exits 1 on false, which is how you test JSON booleans under set -e. Without -e, jq prints false and exits 0, and your if reads the string, not the status.
  • --arg passes 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.ini

Pitfalls

  • sed -i changes inode and ownership context — on a hardlinked file the other link keeps the old content; check ls -i if "my edit didn't take" is the symptom.
  • grep pattern file vs grep -q: the quiet flag exits on first match — right for if, wrong for output you then pipe.
  • jq absent 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.
  • awk default field splitting collapses runs of whitespace and trims edges — different from cut, which honors exact delimiter positions; awk is right for ragged logs, cut -d, -f3 for strict columns.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.