Skip to content
$ lynuxpro
← Bash Scripting

LESSON 8 OF 17 · INTERMEDIATE · 22 MIN

Text processing with grep, sed and awk

HOW IT WORKSA log-analysis pipeline

access.log12 linesgrepkeep matching linesawkpick and sum fieldssort | uniq -ccountsededit textReporttop errors
1/6

Logs are lines of text with fields separated by spaces. Small tools, chained with pipes, answer questions fast.

10.0.0.7 - - [28/Nov/2026…] "GET /api/orders HTTP/1.1" 500 87

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.log
SHELLbashutf-8 · 2L
10.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.log
OUTPUTterminalutf-8 · 4L

Split 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.log
SHELLbashutf-8 · 1L
2026-11-28T09:06:02Z ERROR database connection timeout host=db12026-11-28T09:15:10Z ERROR payment service returned 503
OUTPUTterminalutf-8 · 2L

The options you will use every day:

OptionEffect
-iignore case
-vinvert: lines that do not match
-ccount matching lines
-nshow line numbers
-oprint only the matching part
-Eextended regular expressions (+, ?, |, ())
-wmatch whole words only
-rsearch folders recursively
-llist only file names that match
-qquiet, just set the exit code
-A N / -B N / -C Nshow 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 /etc
SHELLbashutf-8 · 6L
24: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.conf
OUTPUTterminalutf-8 · 14L

Find 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.log
SHELLbashutf-8 · 1L
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.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"
OUTPUTterminalutf-8 · 3L

A quick regular expression primer

PatternMatches
.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:]'
SHELLbashutf-8 · 4L
root:/bin/bashdaemon:/usr/sbin/nologinwww-data:/usr/sbin/nologin      6 200      2 500      1 502      1 404      1 403      1 201web1web2db1prod-server
OUTPUTterminalutf-8 · 13L
  • cut -d DELIM -f FIELDS picks columns from delimited text.
  • sort sorts lines; -n numeric, -r reverse, -k2 by the second field, -t, with a comma separator, -u unique, -h human sizes like 2G.
  • uniq -c counts adjacent duplicate lines, which is why you always sort first.
  • tr translates or deletes characters; tr -d '\r' removes Windows line endings.
  • wc -l counts lines, -w words, -c bytes.

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/'
SHELLbashutf-8 · 3L
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
OUTPUTterminalutf-8 · 7L
  • Without g, only the first match on each line is replaced; with g, 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|'.
sed -n '2,3p' /etc/hostssed -n '/ERROR/p' /var/log/app/app.logsed '/^127/d' /etc/hostssed '1d' servers.csv
SHELLbashutf-8 · 4L
10.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
OUTPUTterminalutf-8 · 12L
  • -n stops sed printing every line automatically; p then 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/.
  • d deletes. 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.copy
SHELLbashutf-8 · 3L
10.0.2.20 db1
OUTPUTterminalutf-8 · 1L

On 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/passwd
SHELLbashutf-8 · 3L
10.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
OUTPUTterminalutf-8 · 8L
  • 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 print inserts 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 | sort
SHELLbashutf-8 · 3L
total bytes: 55046average: 4587.2 bytes over 12 requestsprod 16staging 2tools 16
OUTPUTterminalutf-8 · 5L
  • NR is the current line number (the total, inside END).
  • printf formats like C: %d integer, %s string, %.1f one decimal, %-10s left-aligned in 10 characters.
  • cpu[$2] += $4 uses 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.log
SHELLbashutf-8 · 2L
500 /api/orders500 /api/orders403 /admin502 /api/orders404 /favicon.ico
OUTPUTterminalutf-8 · 5L

Choosing 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: jq for JSON, yq for YAML. Regexes on JSON break easily.
echo '{"name":"checkout","replicas":3,"ready":true}' | jq -r '.name'
SHELLbashutf-8 · 1L

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 '['
SHELLbashutf-8 · 3L
      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:30
OUTPUTterminalutf-8 · 6L

In 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 $1 first. Use single quotes.
  • uniq without sort: duplicates that are not next to each other are not counted together.
  • sed -i without testing: one wrong regex rewrites a config file. Run without -i first.
  • cut on space-aligned output: cut -d' ' breaks when there are several spaces between columns. Use awk '{print $2}', which splits on any run of whitespace.
  • Parsing JSON or YAML with grep and sed: use jq and yq.
  • cat file | grep: works, but grep pattern file is simpler and faster.

Practice

  1. Count how many requests in the access log returned 200.
  2. List the unique paths requested, sorted alphabetically.
  3. Use sed to print only the last line of /etc/passwd (hint: the $ address).
  4. Use awk to print the user names from /etc/passwd whose shell ends in nologin.
  5. From servers.csv, print the name of the server with the most CPUs using sort with -t, and -k4.
  6. 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.json
OUTPUTterminalutf-8 · 11L

Key takeaways

  • grep finds lines, sed edits them, awk works with fields and numbers.
  • sort | uniq -c | sort -rn answers "how many of each" for any column.
  • Quote patterns and awk programs with single quotes; pass variables to awk with -v.
  • Test sed edits before using -i on real files.
  • For JSON and YAML, use jq and yq instead of regexes.