DEVOPS, SRE AND CLOUD · PART 1 · LINUX, FROM THE INSIDE · SHELL · 13 OF 187

grep, sed, awk and jq for DevOps, With Examples

The four text tools that turn logs and API output into answers, run on a 200,000-line, 16.6 MB access log in ShopRung's format and on ShopRung's JSON API: grep to find lines (0.020 s), awk to work with columns (status codes, top failing paths, average latency in 0.1 s), sed to edit streams (masking IP addresses), jq for JSON, and a real trap: grep ' 500 ' counted 4,011 lines but only 3,986 were HTTP 500s.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
1 / 12

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • grep: lines
  • awk: columns and sums
  • sed: stream edits
  • jq: JSON
  • sort | uniq -c | sort -rn

Notes

The data

Our log has one request per line in the common web server format, two hundred thousand lines, sixteen point six megabytes, generated in ShopRung's style for this lesson. Split on spaces, field one is the client address, field seven the path, field nine the status code, field ten the size in bytes and field eleven the duration. Knowing which field is which is the whole trick for awk.

Our access.log
10.0.1.26 - - [01/Dec/2026:
  10:00:00 +0530] "GET /login
  HTTP/1.1" 200 1386 842ms

field  1  client IP
field  7  path
field  9  status code
field 10  bytes
field 11  duration

grep

grep prints the lines that match a pattern. Minus c counts them instead: lines containing space five hundred space, four thousand and eleven, found in twenty milliseconds. Minus i ignores case, minus v inverts the match, minus E allows extended patterns like alternatives, minus r searches whole folders, and minus A and minus B show lines after and before each match, which is how you see the stack trace around an exception.

grep (our runs)
$ grep -c ' 500 ' access.log
4011       in 0.020 s
$ grep -i error app.log
$ grep -v health access.log
$ grep -E '" (500|502|503) '
$ grep -r "timeout" /etc/nginx
$ grep -A3 -B1 Exception app.log

The trap

But was that number right? awk can compare field nine exactly, and it found three thousand nine hundred and eighty six real HTTP five hundreds. Twenty five lines more had matched grep because their response size, field ten, was exactly five hundred bytes. This is a real lesson: a text search matches text anywhere on the line. When the question is about a column, use a tool that understands columns.

Count the 500s, properly
$ grep -c ' 500 ' access.log
4011
$ awk '$9==500' access.log | wc -l
3986

25 extra lines: a response
  SIZE of exactly 500 bytes
  matched the text pattern

awk

awk splits each line into fields named dollar one, dollar two and so on, and runs a small program on each line. Print field nine, sort, count with uniq, sort again, and you have every status code with its count: a hundred and eighty thousand two hundreds, about eight thousand four oh fours, and nearly four thousand five hundreds. A second awk strips the m s from field eleven, sums it, and divides by the number of lines: an average of four hundred and fifty milliseconds, in a tenth of a second.

awk (our runs)
$ awk '{print $9}' access.log
  | sort | uniq -c | sort -rn
 180013 200    7949 404
   6043 201    3986 500
   2009 302
$ awk '{gsub("ms","",$11);
  s+=$11} END {print s/NR}'
avg 450.1 ms     in 0.100 s

Answer the question

Now the incident questions. Which pages fail? Filter field nine equals five hundred, print the path, count: about six hundred each for product three, the home page and the health check, so the errors are spread out, not one broken page. Is it one noisy client? Count by address: the busiest three sent nine hundred and thirty, nine hundred and ten and nine hundred and six requests, close to each other, so no single abuser. Two lines of shell, two clear answers.

Two quick answers
$ awk '$9==500 {print $7}'
  access.log | sort | uniq -c
  | sort -rn | head -3
  600 /api/products/3
  586 /
  580 /api/health
$ awk '{print $1}' | sort |
  uniq -c | sort -rn | head -3
  930, 910, 906 requests

sed

sed edits text as it streams through. Its most used command is s, substitute: here a pattern for an IP address replaced with x dot x dot x dot x, so a log can be shared without personal data. sed minus n with p prints only matching lines, like grep. And sed minus i edits a file in place, which is how many scripts change a config value. Test without minus i first, or keep a backup with minus i dot bak.

sed (our run)
$ sed -E 's/\b([0-9]{1,3}\.){3}
  [0-9]{1,3}\b/x.x.x.x/'
x.x.x.x - - [01/Dec/2026:...]
  "GET /login HTTP/1.1" 200
$ sed -n '/ 500 /p'  print matches
$ sed -i 's/old/new/' file
  edits a file in place

jq

APIs, cloud command line tools and Kubernetes all speak JSON, and jq is grep and awk for JSON. Ask ShopRung's products API for the count: twelve. Then list every item priced above twenty dollars, printing its name and price: five products, starting with the Testing Field Guide at twenty four ninety nine. Minus r prints raw text without quotes. You will use jq constantly with the AWS command line and kubectl.

jq on ShopRung (our runs)
$ curl -s :8080/api/products
  | jq .count
12
$ ... | jq -r '.items[]
  | select(.priceCents > 2000)
  | "\(.name) \(.price)"'
Testing Field Guide $24.99
Works On My Machine Hoodie $49.99
... 5 products

Build an array

jq can also build new JSON, ready for the next tool. Wrap the filter in square brackets and you get an array: the five SKUs with fewer than twenty in stock. The same pattern works on any JSON: list pod names from kubectl, or instance IDs from the AWS command line. Part eleven later replaces some of this with dashboards, but on an unknown server at three in the morning, these four tools are always there.

Low stock SKUs (our run)
$ ... | jq -c '[.items[]
  | select(.stock < 20) | .sku]'
["BK-103","MG-202","TS-302",
 "KB-401","HD-403"]

kubectl get pods -o json |
  jq '.items[].metadata.name'
aws ec2 describe-instances
  | jq '.Reservations[]...'

Common mistakes

Mistakes. Grepping for a number that can appear in other columns, as you saw. Running sed minus i on a real config without testing first. Using uniq without sorting first, since it only merges neighbouring lines. Parsing JSON with grep and sed instead of jq. Piping cat into grep when grep can read the file. And forgetting minus r in jq, so your script receives values wrapped in quotes.

Avoid these
  • grep for a number that can appear in other columns
  • sed -i with no test or backup
  • uniq without sort first
  • parsing JSON with grep/sed
  • cat file | grep (just grep file)
  • forgetting -r in jq: quotes

Say it like this

In the interview: awk with field nine equal to five hundred, print field one, then sort, uniq minus c, sort minus r n, head minus five. I match the status column rather than grepping the text, because a response of exactly five hundred bytes would also match. For JSON from APIs or kubectl I use jq, for example selecting items with stock below twenty.

In the interview
  • "awk '$9==500 {print $1}'
  • access.log | sort | uniq -c |
  • sort -rn | head -5. I match the status field, not the text, so a 500-byte response does not count. For JSON I use jq, for example jq '.items[] | select
  • (.stock < 20)'."

Interview questions

Q1Count HTTP 500 responses in an access log.

awk '$9==500' access.log | wc -l (match the status field). grep ' 500 ' can over-count when 500 appears in another column, such as the response size.

Q2Top 5 client IPs by requests?

awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -5.

Q3What does sed -i do?

Edits the file in place. Test the expression first, or use -i.bak to keep a backup.

Q4Why sort before uniq?

uniq only collapses adjacent duplicate lines, so input must be sorted for counts to be correct.

Q5How do you get a field from JSON in a script?

With jq, for example curl -s url | jq -r '.items[0].name'; -r prints raw strings without quotes.

Q6How do you see lines around a match?

grep -A N for lines after, -B N for lines before, or -C N for both, for example the stack trace around an exception.

Q7How do you compute an average of a column?

awk '{s+=$N} END {print s/NR}' file (strip units first, for example with gsub).

Q8How do you mask IP addresses before sharing a log?

sed -E 's/\b([0-9]{1,3}\.){3}[0-9]{1,3}\b/x.x.x.x/g' access.log.