Text processing: grep, sed and awk
Log files, CSV exports, config files, command output: on a server, almost everything is text. Three classic tools handle nearly every text job:
| Tool | Best at |
|---|---|
grep |
Finding lines that match a pattern |
sed |
Editing text: replace, delete, insert lines |
awk |
Columns and calculations: totals, reports, reformatting |
All the examples below use these two sample files. Create them first:
cat > access.log <<'EOF'
192.168.1.10 - - [22/Nov/2026:10:01:12 +0000] "GET /index.html HTTP/1.1" 200 5120
192.168.1.11 - - [22/Nov/2026:10:01:15 +0000] "GET /about.html HTTP/1.1" 200 2048
10.0.0.5 - - [22/Nov/2026:10:02:01 +0000] "POST /api/login HTTP/1.1" 401 128
192.168.1.10 - - [22/Nov/2026:10:02:30 +0000] "GET /missing.png HTTP/1.1" 404 256
10.0.0.5 - - [22/Nov/2026:10:03:44 +0000] "POST /api/login HTTP/1.1" 200 512
192.168.1.12 - - [22/Nov/2026:10:04:02 +0000] "GET /index.html HTTP/1.1" 200 5120
10.0.0.7 - - [22/Nov/2026:10:05:10 +0000] "GET /api/orders HTTP/1.1" 500 64
192.168.1.10 - - [22/Nov/2026:10:06:55 +0000] "GET /about.html HTTP/1.1" 304 0
EOF
cat > sales.csv <<'EOF'
date,region,product,units,price
2026-11-01,north,keyboard,3,49.50
2026-11-01,south,mouse,10,19.99
2026-11-02,north,monitor,2,229.00
2026-11-02,east,keyboard,5,49.50
2026-11-03,south,monitor,1,229.00
2026-11-03,north,mouse,7,19.99
EOF
wc -l access.log sales.csv8 access.log 7 sales.csv 15 total
grep: find lines
grep "POST" access.log
echo "---"
grep -c " 200 " access.log
grep -v "192.168" access.log | cut -d' ' -f1
echo "---"
grep -i "MISSING" access.log
grep -n "500" access.log10.0.0.5 - - [22/Nov/2026:10:02:01 +0000] "POST /api/login HTTP/1.1" 401 128 10.0.0.5 - - [22/Nov/2026:10:03:44 +0000] "POST /api/login HTTP/1.1" 200 512 --- 4 10.0.0.5 10.0.0.5 10.0.0.7 --- 192.168.1.10 - - [22/Nov/2026:10:02:30 +0000] "GET /missing.png HTTP/1.1" 404 256 7:10.0.0.7 - - [22/Nov/2026:10:05:10 +0000] "GET /api/orders HTTP/1.1" 500 64
| Option | Meaning |
|---|---|
-i |
Ignore upper/lowercase |
-v |
Invert: lines that don't match |
-c |
Count matching lines |
-n |
Show line numbers |
-o |
Print only the matching part |
-w |
Match whole words only |
-r |
Search every file in a folder, recursively |
-l |
Print only the names of files that match |
-q |
Quiet: no output, just the exit code (for if) |
-A 2 / -B 2 / -C 2 |
Also show 2 lines after / before / around each match |
-E |
Extended regular expressions |
Regular expressions
grep -E (and sed -E, and awk) understand regular expressions: patterns that describe text.
grep -E '" (4|5)[0-9]{2} ' access.log
echo "---"
grep -oE '^[0-9.]+' access.log | sort | uniq -c | sort -rn
echo "---"
grep -oE '/api/[a-z]+' access.log | sort -u10.0.0.5 - - [22/Nov/2026:10:02:01 +0000] "POST /api/login HTTP/1.1" 401 128
192.168.1.10 - - [22/Nov/2026:10:02:30 +0000] "GET /missing.png HTTP/1.1" 404 256
10.0.0.7 - - [22/Nov/2026:10:05:10 +0000] "GET /api/orders HTTP/1.1" 500 64
---
3 192.168.1.10
2 10.0.0.5
1 192.168.1.12
1 192.168.1.11
1 10.0.0.7
---
/api/login
/api/orders| Pattern | Matches |
|---|---|
. |
Any one character |
^ / $ |
Start / end of the line |
[0-9], [a-z], [^ ] |
One character from a set (^ inside means "not") |
* / + / ? |
The previous item 0 or more / 1 or more / 0 or 1 times |
{2}, {2,4} |
Exactly 2 / between 2 and 4 times |
(a|b) |
a or b |
\. |
A literal dot |
The second command is a real-world favourite: which IP addresses hit the server most?
Searching code
mkdir -p app/src && printf 'const url = "http://api";\n// TODO: add retries\n' > app/src/client.js
printf 'def main():\n pass # TODO: implement\n' > app/src/main.py
grep -rn "TODO" app
grep -rl "http://" appapp/src/client.js:2:// TODO: add retries app/src/main.py:2: pass # TODO: implement app/src/client.js
(For big codebases, ripgrep (rg) is a faster grep that skips .gitignored files automatically.)
sed: edit streams
sed reads text line by line, applies editing commands, and prints the result. The most used command is substitute, s/old/new/:
echo "hello world, hello bash" | sed 's/hello/goodbye/'
echo "hello world, hello bash" | sed 's/hello/goodbye/g'
sed 's/HTTP\/1.1/HTTP\/2/' access.log | head -2
sed 's|/api/|/v2/api/|' access.log | grep v2goodbye world, hello bash goodbye world, goodbye bash 192.168.1.10 - - [22/Nov/2026:10:01:12 +0000] "GET /index.html HTTP/2" 200 5120 192.168.1.11 - - [22/Nov/2026:10:01:15 +0000] "GET /about.html HTTP/2" 200 2048 10.0.0.5 - - [22/Nov/2026:10:02:01 +0000] "POST /v2/api/login HTTP/1.1" 401 128 10.0.0.5 - - [22/Nov/2026:10:03:44 +0000] "POST /v2/api/login HTTP/1.1" 200 512 10.0.0.7 - - [22/Nov/2026:10:05:10 +0000] "GET /v2/api/orders HTTP/1.1" 500 64
gat the end replaces every match on the line, not just the first.- Any character can be the separator:
s|a|b|saves escaping/in paths.
Other sed commands
sed -n '2,3p' sales.csv # print only lines 2–3
echo "---"
sed '1d' sales.csv | head -2 # delete line 1 (the header)
echo "---"
sed '/south/d' sales.csv # delete lines matching a pattern
echo "---"
sed -E 's/^([0-9-]+),([a-z]+)/\2 on \1/' sales.csv | sed -n '2p'2026-11-01,north,keyboard,3,49.50 2026-11-01,south,mouse,10,19.99 --- 2026-11-01,north,keyboard,3,49.50 2026-11-01,south,mouse,10,19.99 --- date,region,product,units,price 2026-11-01,north,keyboard,3,49.50 2026-11-02,north,monitor,2,229.00 2026-11-02,east,keyboard,5,49.50 2026-11-03,north,mouse,7,19.99 --- north on 2026-11-01,keyboard,3,49.50
In sed -E, ( ) captures text and \1, \2 put it back: here, swapping two columns.
Editing files in place
printf "port=3000\nhost=localhost\ndebug=true\n" > app.conf
sed -i 's/^port=.*/port=8080/; s/^debug=true/debug=false/' app.conf
cat app.conf
sed -i.bak 's/localhost/0.0.0.0/' app.conf
ls app.conf*port=8080 host=localhost debug=false app.conf app.conf.bak
-i changes the file directly; -i.bak keeps a backup first. This is how scripts change config files on servers.
⚠️ On macOS,
sed -ineeds an argument:sed -i '' 's/a/b/' file. GNU sed (Linux) and BSD sed (macOS) differ in small ways like this. Test scripts on the system they'll run on.
awk: columns and calculations
awk splits every line into fields: $1, $2, … ($0 is the whole line, NF the number of fields, NR the line number). Its programs look like pattern { action }:
awk '{ print $1, $9 }' access.log | head -3
echo "---"
awk '$9 >= 400 { print NR": "$9, $7 }' access.log
echo "---"
awk -F, 'NR > 1 { print $3 }' sales.csv | sort -u192.168.1.10 200 192.168.1.11 200 10.0.0.5 401 --- 3: 401 /api/login 4: 404 /missing.png 7: 500 /api/orders --- keyboard monitor mouse
- Fields are separated by spaces by default;
-F,splits on commas. $9 >= 400is the pattern: the action runs only for lines where it's true.NR > 1skips the header line.
Sums, averages and grouping
This is where awk shines:
awk '{ bytes += $10 } END { print "total bytes:", bytes }' access.log
awk -F, 'NR > 1 { revenue += $4 * $5 } END { printf "revenue: %.2f\n", revenue }' sales.csv
echo "--- revenue by region"
awk -F, 'NR > 1 { r[$2] += $4 * $5 } END { for (k in r) printf "%-6s %8.2f\n", k, r[k] }' sales.csv | sort
echo "--- requests per status"
awk '{ n[$9]++ } END { for (s in n) print s, n[s] }' access.log | sorttotal bytes: 13248 revenue: 1422.83 --- revenue by region east 247.50 north 746.43 south 428.90 --- requests per status 200 4 304 1 401 1 404 1 500 1
END { … }runs once, after the last line. (BEGIN { … }runs before the first.)- Variables start at 0, so
bytes += $10just works. r[$2] += …is an associative array keyed by region: a "group by" in one line.
Reformatting
awk -F, 'BEGIN { OFS=" | " } NR > 1 { print $1, toupper($3), $4 " units" }' sales.csv | head -3
awk -F: '$3 >= 1000 && $3 < 65000 { print $1 " has home " $6 }' /etc/passwd2026-11-01 | KEYBOARD | 3 units 2026-11-01 | MOUSE | 10 units 2026-11-02 | MONITOR | 2 units ubuntu has home /home/ubuntu you has home /home/you
OFS is the output field separator used between the values in print a, b.
Putting it together
A daily report from the log, in one small script:
#!/usr/bin/env bash
log=${1:-access.log}
echo "Report for $log"
echo " requests: $(wc -l < "$log")"
echo " unique IPs: $(awk '{ print $1 }' "$log" | sort -u | wc -l)"
echo " errors (4xx/5xx): $(awk '$9 >= 400' "$log" | wc -l)"
echo " top page: $(awk '{ print $7 }' "$log" | sort | uniq -c | sort -rn | head -1 | awk '{ print $2 " (" $1 " hits)" }')"
echo " data sent: $(awk '{ s += $10 } END { printf "%.1f KB", s / 1024 }' "$log")"bash report.shReport for access.log requests: 8 unique IPs: 5 errors (4xx/5xx): 3 top page: /index.html (2 hits) data sent: 12.9 KB
Other tools worth knowing
| Tool | Does |
|---|---|
cut -d, -f2 |
Pick columns (simpler than awk for one column) |
sort -t, -k4 -n |
Sort by a column, numerically |
uniq -c |
Count repeated adjacent lines (sort first) |
tr 'a-z' 'A-Z', tr -d '\r' |
Translate or delete characters (fix Windows line endings!) |
paste, join, column -t |
Combine files, line up columns |
jq |
The awk for JSON: curl … | jq '.items[].name' |
echo '{"users":[{"name":"Asha","admin":true},{"name":"Ravi","admin":false}]}' | jq -r '.users[] | select(.admin) | .name'
column -t -s, sales.csv | head -3Asha date region product units price 2026-11-01 north keyboard 3 49.50 2026-11-01 south mouse 10 19.99
Practice
- Print every line of
access.logfrom the IP10.0.0.5, then count them. - Use
sedto change everynorthinsales.csvtoNand save the result assales-short.csv. - Use
awkto print the total number of units sold per product. - Find the busiest minute in
access.log(hint:grep -oE '[0-9]{2}:[0-9]{2}:[0-9]{2}'and cut off the seconds).
1.Which command counts the lines containing "error"?
2.What does the g do in sed 's/a/b/g'?
3.In awk, what is $3?
4.Which awk program prints the sum of the second column?