Skip to content

Lesson 11 of 13 · 28m

The Unix Text Toolkit: grep, sed, awk, and jq

Each tool's lane, the flags you'll actually use, and the incident-response pipelines that answer questions in seconds instead of scripts.

It's 2 a.m., the API is throwing 502s, and you've got a 3 GB nginx access log. The question is "which clients are getting errors, and since when?" A pipeline answers that in ten seconds. A Python script answers it in fifteen minutes, after you debug the script. The Unix toolkit is less about regex and more about composition: each tool does one job, and the pipe glues them.

Know the lanes

Text pipeline lanes

  • grep selects lines.
  • sed edits a stream: substitute, delete, print ranges.
  • awk works with fields and aggregates: columns, sums, counts, grouping.
  • jq handles structured JSON. Once the data is JSON, stop treating it as lines.

grep: the flags that matter

grep -rn --include='*.py' 'verify=False' src/          # recursive, line numbers, only .py
grep -c '" 502 ' /var/log/nginx/access.log              # count matching lines
grep -oE 'request_id=[0-9a-f-]{36}' app.log | sort -u   # print only the match, not the line
grep -B2 -A15 'Traceback' worker.log                    # context around each hit
grep -F -f blocked_ips.txt access.log                   # ten thousand fixed strings, one pass

-F is the sleeper flag: fixed strings, no regex, and multi-pattern search is algorithmically fast on huge pattern files. For source trees, rg respects .gitignore, skips binaries, and runs in parallel — the right default for code. Plain grep is the right default for logs on a box you can't install anything on.

sed: substitutions and ranges

sed -n '/^2025-03-14T09:2/,/^2025-03-14T09:3/p' app.log              # print a time window
sed -E 's/(password|token|secret)=[^& ]+/\1=REDACTED/g' access.log    # scrub before sharing
sed -i.bak -E 's/^#?PermitRootLogin .*/PermitRootLogin no/' /etc/ssh/sshd_config

-i.bak — suffix attached, no space — works on GNU and BSD sed and leaves a backup. On config files, always leave a backup. sshd_config is not the place to discover your pattern ate a line.

awk: fields and aggregation

# Top client IPs getting 5xx. Combined log format: $1=client, $9=status, $10=bytes
awk '$9 ~ /^5/ {print $1}' access.log | sort | uniq -c | sort -rn | head -20

# Bytes served per status code
awk '{bytes[$9] += $10} END {for (s in bytes) printf "%s %d\n", s, bytes[s]}' access.log

# TSV with a header row, explicit separator
awk -F'\t' 'NR > 1 && $4 > 1000 {print $1, $4}' export.tsv

awk is a whole language — match(), gsub(), associative arrays, next. When an awk program grows past one screen it has earned a real file.

The idiom worth memorizing is the filter-aggregate chain: awk selects and sums, sort | uniq -c | sort -rn turns a field into a histogram, head -20 shows you the top. "Which clients are 502ing since 09:26" is literally awk '$4 ~ /09:2[6-9]/ && $9 == 502 {print $1}' access.log | sort | uniq -c | sort -rn.

jq: stop grepping JSON

kubectl get pods -A -o json | jq -r '.items[]
  | select(.status.phase != "Running")
  | "\(.metadata.namespace)/\(.metadata.name)  \(.status.phase)"'

jq -c 'select(.level == "error" and .latency_ms > 500)' app.jsonl   # JSON-lines logs
jq --arg uid "$USER_ID" 'select(.user_id == $uid)' app.jsonl         # pass shell values safely
jq -r '.items[] | .metadata.name' pods.json | xargs -I{} kubectl describe pod {}  # iterate safely

jq has its own regexes inside (test, match, sub — Oniguruma under the hood), but you'll rarely need them: the structure already did the parsing.

Field notes

  • uniq collapses only adjacent duplicates. It's always sort | uniq -c | sort -rn.
  • Single-quote awk and jq programs, or the shell eats $1 and $uid before the tool sees them.
  • Never splice shell variables into a jq or awk program string — use jq --arg and awk -v name="$val".
  • In scripts, set -o pipefail. Otherwise a failed grep mid-pipeline reports success and your cron job silently does nothing.
  • sort -h sorts human-readable sizes (4K, 900M); sort -V sorts version numbers. Both GNU.

Keep reading

Related articles from the SudoSecurity blog.