Logs, config files, CSV exports, command output: almost everything a DevOps engineer reads is lines of text. Three classic tools let you search, edit and summarise that text in seconds, often in a single line: grep finds lines, sed edits them and awk treats them as columns of data. Add cut, sort, uniq, tr and wc, and you can answer most "what is happening on this server?" questions without opening an editor.
The examples use the practice terminal's nginx access log. Look at it first:
head -n 3 /var/log/nginx/access.logwc -l /var/log/nginx/access.log10.0.0.5 - - [28/Nov/2026:09:01:00 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/8.5.0"10.0.0.7 - - [28/Nov/2026:09:01:03 +0000] "GET /api/orders HTTP/1.1" 500 87 "-" "curl/8.5.0"10.0.0.5 - - [28/Nov/2026:09:01:09 +0000] "GET /health HTTP/1.1" 200 2 "-" "curl/8.5.0"12 /var/log/nginx/access.logSplit on spaces, field 1 is the client IP, field 7 is the path, field 9 is the HTTP status and field 10 is the response size in bytes.
In simple words
- grep: finds lines that match a pattern.
- Regular expression: a pattern language for matching text, such as ^ for the start of a line.
- sed: edits text as it flows past, most often to find and replace.
- awk: a small language for working with columns, such as printing the 3rd field or adding numbers up.
grep: find lines
grep PATTERN FILE prints every line that matches:
grep ERROR /var/log/app/app.log2026-11-28T09:06:02Z ERROR database connection timeout host=db12026-11-28T09:15:10Z ERROR payment service returned 503The options you will use every day:
| Option | Effect |
|---|---|
-i | ignore case |
-v | invert: lines that do not match |
-c | count matching lines |
-n | show line numbers |
-o | print only the matching part |
-E | extended regular expressions (+, ?, |, ()) |
-w | match whole words only |
-r | search folders recursively |
-l | list only file names that match |
-q | quiet, just set the exit code |
-A N / -B N / -C N | show N lines after / before / around |
grep -c ERROR /var/log/app/app.loggrep -n WARN /var/log/app/app.loggrep -v INFO /var/log/app/app.loggrep -E 'ERROR|WARN' /var/log/app/app.loggrep -oE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' /var/log/nginx/access.log | sort -ugrep -rl proxy_pass /etc24:2026-11-28T09:06:03Z WARN retrying connection attempt=12026-11-28T09:06:02Z ERROR database connection timeout host=db12026-11-28T09:06:03Z WARN retrying connection attempt=12026-11-28T09:15:10Z ERROR payment service returned 5032026-11-28T09:06:02Z ERROR database connection timeout host=db12026-11-28T09:06:03Z WARN retrying connection attempt=12026-11-28T09:15:10Z ERROR payment service returned 50310.0.0.1210.0.0.2110.0.0.510.0.0.710.0.0.9/etc/nginx/nginx.confFind all server errors (status 5xx). The pattern matches a space, a 5, two digits and a space:
grep -E '" 5[0-9]{2} ' /var/log/nginx/access.log10.0.0.7 - - [28/Nov/2026:09:01:03 +0000] "GET /api/orders HTTP/1.1" 500 87 "-" "curl/8.5.0"10.0.0.7 - - [28/Nov/2026:09:02:20 +0000] "GET /api/orders HTTP/1.1" 500 87 "-" "curl/8.5.0"10.0.0.7 - - [28/Nov/2026:09:04:30 +0000] "GET /api/orders HTTP/1.1" 502 157 "-" "curl/8.5.0"A quick regular expression primer
| Pattern | Matches |
|---|---|
. | any one character |
* | the previous item zero or more times |
+ | one or more times (with -E) |
? | zero or one time (with -E) |
^ / $ | start / end of the line |
[abc] / [0-9] | one character from a set or range |
[^0-9] | one character not in the set |
{3} | exactly three times (with -E) |
(a|b) | a or b (with -E) |
\. | a literal dot |
Always put patterns in single quotes so Bash does not expand *, $ or ? before grep sees them.
cut, sort, uniq, wc, tr: the small tools
These do one simple job each and combine beautifully:
cut -d: -f1,7 /etc/passwd | head -n 3cut -d' ' -f9 /var/log/nginx/access.log | sort | uniq -c | sort -rnecho "web1 web2 db1" | tr ' ' '\n'echo "Prod-Server" | tr '[:upper:]' '[:lower:]'root:/bin/bashdaemon:/usr/sbin/nologinwww-data:/usr/sbin/nologin 6 200 2 500 1 502 1 404 1 403 1 201web1web2db1prod-servercut -d DELIM -f FIELDSpicks columns from delimited text.sortsorts lines;-nnumeric,-rreverse,-k2by the second field,-t,with a comma separator,-uunique,-hhuman sizes like2G.uniq -ccounts adjacent duplicate lines, which is why you alwayssortfirst.trtranslates or deletes characters;tr -d '\r'removes Windows line endings.wc -lcounts lines,-wwords,-cbytes.
sort | uniq -c | sort -rn is probably the most useful pipeline in operations: "how many of each, biggest first".
sed: edit text as it streams
sed reads lines, applies editing commands and prints the result. It does not change the file unless you ask it to.
Substitute: s/old/new/
sed 's/web/app/' /etc/hostssed 's/web/app/g' /etc/hosts | grep appecho "version=1.4.2" | sed -E 's/([0-9]+)\.([0-9]+)\.([0-9]+)/\1.\2.99/'127.0.0.1 localhost10.0.1.10 app110.0.1.11 app210.0.2.10 db110.0.1.10 app110.0.1.11 app2version=1.4.99- Without
g, only the first match on each line is replaced; withg, all of them. - With
-E, parentheses capture groups that you reuse as\1,\2. &in the replacement means "the whole match":sed 's/[0-9]\+/[&]/'.- If the pattern contains
/, use another delimiter:sed 's|/var/log|/data/log|'.
Print and delete lines
sed -n '2,3p' /etc/hostssed -n '/ERROR/p' /var/log/app/app.logsed '/^127/d' /etc/hostssed '1d' servers.csv10.0.1.10 web110.0.1.11 web22026-11-28T09:06:02Z ERROR database connection timeout host=db12026-11-28T09:15:10Z ERROR payment service returned 50310.0.1.10 web110.0.1.11 web210.0.2.10 db1web1,prod,10.0.1.10,4web2,prod,10.0.1.11,4db1,prod,10.0.2.10,8web-stg,staging,10.1.1.10,2ci-runner,tools,10.2.0.5,16-nstops sed printing every line automatically;pthen prints only what you choose.- An address in front of a command limits it: a line number (
3), a range (2,5),$for the last line, or a/regex/. ddeletes.sed '1d'is a quick way to drop a CSV header.
Editing files in place
-i writes the result back into the file. It is how scripts update config files:
cp /etc/hosts hosts.copysed -i 's/10.0.2.10/10.0.2.20/' hosts.copygrep db1 hosts.copy10.0.2.20 db1On a real server, test the command without -i first, or use -i.bak to keep a backup copy (hosts.bak). On macOS, sed -i needs an argument: sed -i '' 's/a/b/' file.
awk: a small language for columns
awk splits every line into fields, $1, $2 …, with $0 being the whole line and NF the number of fields. A program is a list of pattern { action } rules, run for every line.
awk '{print $1, $9}' /var/log/nginx/access.log | head -n 3awk '$9 >= 500 {print $1, $7, $9}' /var/log/nginx/access.logawk -F: '$3 >= 1000 {print $1 " uses " $7}' /etc/passwd10.0.0.5 20010.0.0.7 50010.0.0.5 20010.0.0.7 /api/orders 50010.0.0.7 /api/orders 50010.0.0.7 /api/orders 502lynuxpro uses /bin/bashdeploy uses /bin/bash- Without a pattern, the action runs on every line. Without an action, matching lines are printed.
- Patterns can compare fields (
$9 >= 500), match regexes (/ERROR/,$7 ~ /^\/api/) or combine with&&and||. -F:sets the field separator (here, a colon).- A comma in
printinserts a space; strings next to each other are joined.
Sums, counts and END
awk keeps variables between lines, and runs BEGIN before the first line and END after the last. That makes it ideal for totals:
awk '{bytes += $10} END {print "total bytes:", bytes}' /var/log/nginx/access.logawk '{bytes += $10} END {printf "average: %.1f bytes over %d requests\n", bytes/NR, NR}' /var/log/nginx/access.logawk -F, 'NR > 1 {cpu[$2] += $4} END {for (e in cpu) print e, cpu[e]}' servers.csv | sorttotal bytes: 55046average: 4587.2 bytes over 12 requestsprod 16staging 2tools 16NRis the current line number (the total, insideEND).printfformats like C:%dinteger,%sstring,%.1fone decimal,%-10sleft-aligned in 10 characters.cpu[$2] += $4uses an associative array keyed by the second column, the awk version of a "group by".
Passing shell variables into awk
Never paste a shell variable into the awk program text. Pass it with -v:
threshold=400awk -v t="$threshold" '$9 >= t {print $9, $7}' /var/log/nginx/access.log500 /api/orders500 /api/orders403 /admin502 /api/orders404 /favicon.icoChoosing the right tool
- Find lines →
grep. - Pick a column from cleanly delimited data →
cut. - Replace text, or print/delete lines by number or pattern →
sed. - Anything involving fields plus logic, sums, counts or formatting →
awk. - Structured data like JSON or YAML → use a real parser:
jqfor JSON,yqfor YAML. Regexes on JSON break easily.
echo '{"name":"checkout","replicas":3,"ready":true}' | jq -r '.name'Real-world scenario: the 2 a.m. incident report
An alert fires: error rate is up. On the load balancer you need, in under a minute, the failing endpoints, which clients hit them, and how many times:
awk '$9 >= 500 {print $9, $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rnawk '$9 >= 500 {print $1}' /var/log/nginx/access.log | sort | uniq -cgrep -E '" 5[0-9]{2} ' /var/log/nginx/access.log | awk '{print $4}' | tr -d '[' 2 500 /api/orders 1 502 /api/orders 3 10.0.0.728/Nov/2026:09:01:0328/Nov/2026:09:02:2028/Nov/2026:09:04:30In three lines you know it is one endpoint, one client, and when it started. That is enough to page the right team.
Common mistakes
- Double quotes around awk programs:
awk "{print $1}"lets Bash replace$1first. Use single quotes. uniqwithoutsort: duplicates that are not next to each other are not counted together.sed -iwithout testing: one wrong regex rewrites a config file. Run without-ifirst.cuton space-aligned output:cut -d' 'breaks when there are several spaces between columns. Useawk '{print $2}', which splits on any run of whitespace.- Parsing JSON or YAML with grep and sed: use
jqandyq. cat file | grep: works, butgrep pattern fileis simpler and faster.
Practice
- Count how many requests in the access log returned 200.
- List the unique paths requested, sorted alphabetically.
- Use
sedto print only the last line of/etc/passwd(hint: the$address). - Use
awkto print the user names from/etc/passwdwhose shell ends innologin. - From
servers.csv, print the name of the server with the most CPUs usingsortwith-t,and-k4. - Total the CPUs of all servers with awk, skipping the header.
Cheat sheet
grep -iE 'a|b' f grep -v x f grep -c x f grep -o 're' fgrep -rn TODO dir/ grep -q x f && echo foundcut -d, -f1,3 f tr 'a-z' 'A-Z' tr -d '\r'sort | uniq -c | sort -rn sort -t, -k3 -n fsed 's/a/b/g' f sed -E 's/(x)y/\1z/' fsed -n '5,10p' f sed '/re/d' f sed -i.bak 's/a/b/' fawk '{print $1, $NF}' f awk -F: '$3>=1000' fawk '/re/ {n++} END {print n}' fawk -v x="$var" '$2 == x' fawk '{s[$1]+=$2} END {for (k in s) print k, s[k]}' fjq -r '.items[].name' f.jsonKey takeaways
grepfinds lines,sededits them,awkworks with fields and numbers.sort | uniq -c | sort -rnanswers "how many of each" for any column.- Quote patterns and awk programs with single quotes; pass variables to awk with
-v. - Test
sededits before using-ion real files. - For JSON and YAML, use
jqandyqinstead of regexes.