# Text processing: get answers out of logs

grep, cut, sort, uniq, tr, wc, awk and sed, chained with pipes, on a real access log. Find the errors, the noisy clients and the broken endpoint in one line.

Course: [Linux & Bash for DevOps](https://devops.rajeev.pro/courses/linux), lesson 5. About 35 minutes, beginner. Source: https://devops.rajeev.pro/courses/linux/05-text-processing

## What you will learn

- Search files with grep, including regular expressions, counts and inverted matches
- Cut, sort, count and de-duplicate lines to turn a log into numbers
- Change characters with tr and edit lines with sed, including in-place with a backup
- Use awk to pick fields, filter rows and add up a column
- Build a pipeline step by step, checking the output at each stage
- Verify a download with sha256sum, and read compressed logs without unpacking

## The log we'll use

During an incident, an engineer may need to answer "how many errors since 10?" or "which client is sending
the most requests?" Opening a large log and scanning it by eye is slow and easy to miscount. Linux text tools
filter and summarize lines so you can answer with a repeatable command.

This lesson uses one web-server access log. Each line records a request, including a client address, time,
method, path and status. Create it with the mini mission at the bottom, or use an nginx `access.log`:

Start by looking at a few lines so you know the field order before writing a filter. The same tools work on
application logs and command output, but the format determines which patterns are safe. These examples use
the sample access-log format shown here; do not assume another service writes the same fields.

```text
203.0.113.7 - - [13/Oct/2026:10:00:04 +0530] "POST /api/orders HTTP/1.1" 500 312 "-" "curl/8.5.0"
│                │                            │    │           │         │   └ bytes sent  └ client
│                │                            │    │           │         └ status code
│                │                            │    └ path      └ protocol
│                │                            └ method
│                └ time
└ client IP
```

```sh
$ head -n 3 access.log     # first lines: what does the format look like?
$ tail -n 20 access.log    # the newest entries
$ tail -f access.log       # follow live; Ctrl+C stops
$ less access.log          # scroll; /500 searches, q quits
```

## grep: find the lines that matter

`grep` searches text for a fixed string or regular expression and prints matching lines. It is useful when you
know one detail to look for, such as an HTTP status or an error message. `-i` ignores case, `-v` inverts the
match, `-n` adds line numbers, `-r` searches directories recursively, and `-c` counts matching lines.

```sh
$ grep '" 500 ' access.log               # lines with status 500 (quotes avoid matching "1500")
$ grep -c '" 500 ' access.log            # how many
3
$ grep -i error app.log                  # ignore case: Error, ERROR, error
$ grep -v /health access.log | wc -l     # everything except health checks
10
$ grep -n "timeout" app.log              # with line numbers
$ grep -r "listen 80" /etc/nginx/        # search every file in a folder
$ grep -E '" 5[0-9]{2} ' access.log | wc -l   # -E: extended regex, any 5xx status
4
$ grep -oE '"(GET|POST) [^ ]+' access.log | sort | uniq -c | sort -rn | head -3
      4 "POST /api/orders
      2 "GET /health
      2 "GET /
```

The regular-expression pieces you'll use most:

| Pattern            | Matches                                                       |
| ------------------ | ------------------------------------------------------------- |
| `^ERROR` / `done$` | at the start / end of the line                                |
| `.`                | any one character                                             |
| `[0-9]` / `[a-z]`  | one character from a set                                      |
| `a*` / `a+` / `a?` | zero or more / one or more / optional (`+` and `?` need `-E`) |
| `5[0-9]{2}`        | 5 followed by exactly two digits (`-E`)                       |
| `(GET\|POST)`      | either word (`-E`)                                            |

`-o` prints only the matching part of each line, which is how you extract values. Test a pattern
on regex101 before you trust it on a production log.

Use simple patterns first, then add anchors, character classes or repetition only as needed. Quote patterns
that contain spaces or shell metacharacters so Bash passes them to grep unchanged. A common mistake is using
`grep 500` and matching unrelated values such as a byte count; include surrounding context like the quotes in
the example and check a few matching lines before trusting the count.

> **Video.** [Linux Crash Course - The grep Command](https://www.youtube.com/watch?v=Tc_jntovCM0) (Learn Linux TV)

## cut and tr: pick and change characters

`cut` selects fields or character positions from each line. `-d` chooses a delimiter and `-f` selects fields;
it works best when the input has a consistent delimiter. `tr` translates, deletes or squeezes individual
characters. It is not a field parser, so use it for transformations such as case conversion or removing
carriage returns rather than splitting complex formats.

```sh
$ cut -d' ' -f1 access.log | head -n 3      # field 1, splitting on spaces: the client IPs
203.0.113.7
198.51.100.23
203.0.113.7
$ head -n 2 access.log | cut -d'"' -f2      # split on quotes instead: the request
GET / HTTP/1.1
GET /login HTTP/1.1
$ cut -d: -f1,7 /etc/passwd                 # users and their login shells
$ echo "Prod-Web-01" | tr 'A-Z' 'a-z'       # translate characters
prod-web-01
$ echo "a   b    c" | tr -s ' '              # squeeze repeated spaces
a b c
$ tr -d '\r' < windows.txt > unix.txt       # delete characters (Windows line endings)
```

The first example splits on spaces, while the quoted request example splits on double quotes. Delimiter choice
matters: whitespace in a request can shift fields, so do not assume a log format is safely parsed by one
space-separated `cut`. Use `awk` or a log parser when fields are quoted or may contain separators. A common
mistake is editing the source file with redirection that overwrites it; write transformed output to a new file
until you have checked it.

## sort, uniq and wc: turn lines into numbers

These commands turn a list into a summary. `sort` orders lines, `uniq` compares adjacent lines, and `wc`
counts lines, words or bytes. Because `uniq` only combines neighbors, sort the values first when equal entries
may be scattered through the input.

```sh
$ wc -l access.log                                   # lines (-w words, -c bytes)
12 access.log
$ cut -d' ' -f1 access.log | sort | uniq -c | sort -rn | head -3   # busiest clients
      5 203.0.113.7
      3 198.51.100.23
      2 192.0.2.44
$ sort -t: -k3 -n /etc/passwd     # -t separator, -k column, -n as numbers
$ sort -u ips.txt                 # sort and drop duplicates in one go
$ du -sh /var/log/* | sort -h     # -h understands 4K, 12M, 1.1G
```

`sort | uniq -c | sort -rn` is the most useful pipeline in operations: count each distinct value,
biggest first.

In the busiest-client example, the first sort groups identical IP addresses. `uniq -c` prefixes each group
with its count, and the second sort uses numeric reverse order so the largest count appears first. `sort -h`
understands human-readable sizes such as K and M, unlike a plain lexical sort. A common mistake is omitting
the first sort and expecting `uniq -c` to count every repeated value in the file.

## Build a pipeline one step at a time

> **Figure.** A pipeline that finds the busiest clients. access.log has 12 lines. cut keeps only the first field, the IP. sort groups identical IPs together. uniq -c counts each group. sort -rn puts the biggest count first. head -3 keeps the top three: 5 requests from 203.0.113.7, 3 from 198.51.100.23, 2 from 192.0.2.44.
>
> Each tool does one small job. Run the pipeline one step at a time, checking the output as you go.

> **Figure.** Animated, using the lesson's real access log. cut keeps the first field of each of the 12 lines: the client IPs in log order. sort puts identical IPs next to each other. uniq -c turns each group into one line with a count. sort -rn puts the biggest count first. head -3 keeps the top three: 5 requests from 203.0.113.7, 3 from 198.51.100.23 and 2 from 192.0.2.44.
>
> The same pipeline, animated with the real output of each stage: 12 lines in, one answer out.

Don't write the whole pipeline at once. Add one command, look at the output, then add the next.
When a long pipeline gives a strange answer, delete commands from the end until the output makes
sense again.

`tee` lets you keep the middle of a pipeline while it carries on:

```sh
$ grep '" 500 ' access.log | tee errors.log | wc -l    # save the errors AND count them
3
```

## awk and sed

`awk` and `sed` help when grep and cut are no longer enough. **awk** reads one line at a time, splits it into
fields (`$1`, `$2`, and so on; `$NF` is the last field), and can filter or calculate over those fields.
`pattern {action}` runs the action only on matching lines. The default field separator is whitespace; `-F`
changes it.

For each input line, awk evaluates the pattern and then runs the action inside braces. It can accumulate
values and print a summary after the final line. Use it when you need the same field-oriented operation over
many records, but confirm the input format first: the default whitespace separator does not understand every
quoted log format.

```sh
$ awk '{print $9, $7}' access.log | head -n 2       # status and path
200 /
200 /login
$ awk '{print $9}' access.log | sort | uniq -c | sort -rn   # requests per status
      6 200
      3 500
      1 502
      1 404
      1 302
$ awk '$9 >= 500 {print $7}' access.log | sort | uniq -c    # which endpoint is failing?
      4 /api/orders
$ awk '{sum += $10} END {print sum}' access.log     # total bytes sent
21730
$ awk -F: '$3 >= 1000 {print $1}' /etc/passwd       # -F sets the separator: real users
```

**sed** edits a stream of lines: substitute, print or delete.

```sh
$ echo "port = 8080" | sed 's/8080/9090/'         # substitute (first match per line)
port = 9090
$ sed 's/http:/https:/g' site.conf                # g: every match. Prints, changes nothing
$ sed -n '3,4p' access.log                        # print only lines 3 and 4
$ sed '/^#/d' app.conf                            # delete comment lines from the output
$ sed -i.bak 's/8080/9090/g' app.conf             # edit the file in place, keep app.conf.bak
```

> **Preview before -i.** Run every `sed` without `-i` first: it prints the result and leaves the file alone. When the output is right, add `-i.bak`. The `.bak` copy is your one-step undo.

Use awk for field-based reports such as counts and sums. Use sed for simple line substitutions or selecting
and deleting lines. By default, sed prints transformed text without changing the source; `-i` edits the file
in place, so preview first and keep a backup. These tools are not full parsers for arbitrary quoted formats.
A common mistake is assuming awk's whitespace fields match a quoted web-log format; use a parser or explicitly
set and validate field handling when spaces can appear inside fields.

### A few more you'll use

```sh
$ nl app.conf                          # number the lines
$ paste names.txt emails.txt           # join two files side by side
$ split -l 100000 huge.csv part_       # cut a big file into 100,000-line pieces
$ zcat access.log.2.gz | grep '" 500 ' # read a rotated, compressed log (zgrep works too)
$ sha256sum ubuntu.iso                 # fingerprint a file
$ sha256sum -c SHA256SUMS              # check downloads against the published list
ubuntu.iso: OK
```

> **In production.** Logs rotate: today's file is `access.log`, yesterday's `access.log.1`, older ones `access.log.2.gz`. To search the last week, include them: `zgrep '" 500 ' access.log*` reads plain and compressed files alike.

> **Video.** [Linux Crash Course - awk](https://www.youtube.com/watch?v=oPEnvuj9QrI) (Learn Linux TV)

## Mission: Find out why checkout is failing

Support says customers can't place orders. Using only the access log, find how many requests failed, which endpoint is failing, and which client is sending those requests. Save the failed requests to a file for the developers.

- You need: ~/lab5/access.log
- You'll have: ~/lab5/errors.log

```sh
$ mkdir -p ~/lab5 && cd ~/lab5 && cat > access.log <<'EOF'
203.0.113.7 - - [13/Oct/2026:10:00:01 +0530] "GET / HTTP/1.1" 200 5120 "-" "Mozilla/5.0"
198.51.100.23 - - [13/Oct/2026:10:00:03 +0530] "GET /login HTTP/1.1" 200 2048 "-" "Mozilla/5.0"
203.0.113.7 - - [13/Oct/2026:10:00:04 +0530] "POST /api/orders HTTP/1.1" 500 312 "-" "curl/8.5.0"
192.0.2.44 - - [13/Oct/2026:10:00:09 +0530] "GET /health HTTP/1.1" 200 2 "-" "kube-probe/1.31"
203.0.113.7 - - [13/Oct/2026:10:00:10 +0530] "POST /api/orders HTTP/1.1" 500 312 "-" "curl/8.5.0"
198.51.100.23 - - [13/Oct/2026:10:00:12 +0530] "GET /api/orders HTTP/1.1" 200 8192 "-" "Mozilla/5.0"
203.0.113.7 - - [13/Oct/2026:10:00:15 +0530] "POST /api/orders HTTP/1.1" 502 157 "-" "curl/8.5.0"
198.51.100.9 - - [13/Oct/2026:10:00:18 +0530] "GET /wp-login.php HTTP/1.1" 404 153 "-" "python-requests/2.32"
192.0.2.44 - - [13/Oct/2026:10:00:19 +0530] "GET /health HTTP/1.1" 200 2 "-" "kube-probe/1.31"
203.0.113.7 - - [13/Oct/2026:10:00:21 +0530] "POST /api/orders HTTP/1.1" 500 312 "-" "curl/8.5.0"
198.51.100.23 - - [13/Oct/2026:10:00:24 +0530] "GET /logout HTTP/1.1" 302 0 "-" "Mozilla/5.0"
203.0.113.50 - - [13/Oct/2026:10:00:30 +0530] "GET / HTTP/1.1" 200 5120 "-" "Mozilla/5.0"
EOF
$ awk '$9 >= 500' access.log | tee errors.log | wc -l          # how many failed
4
$ awk '$9 >= 500 {print $6, $7}' access.log | sort | uniq -c   # which endpoint
      4 "POST /api/orders
$ awk '$9 >= 500 {print $1}' access.log | sort | uniq -c       # which client
      4 203.0.113.7
```

Every failure is a `POST /api/orders` from one client, so the orders API is failing, and only for
writes: the `GET /api/orders` at 10:00:12 succeeded. That's a far better bug report than
"checkout is broken", and `errors.log` gives the developers the exact requests.

## Try it

- Create the sample `access.log` from the mini mission and count its lines with `wc -l`.
- Show only the failed requests (status 500 to 599) with one `grep -E`.
- List the three busiest client IPs with `cut | sort | uniq -c | sort -rn | head -3`.
- Use `awk` to print just the status code and path of every request.
- Replace `HTTP/1.1` with `HTTP/2` in a copy of the log using `sed -i.bak`, then compare with `diff`.
- Make a checksum with `sha256sum file > file.sha256` and check it with `sha256sum -c`.

## Quiz

1. Why does uniq -c give wrong counts on an unsorted list?
   - It only counts the first 10 lines
   - **It only merges lines that are next to each other, so you sort first** (answer)
   - It ignores numbers
   Why: uniq compares each line with the one before it. sort puts identical lines together, so sort | uniq -c is the classic pair.

2. You want every line of app.log that does NOT contain "health". Which command?
   - grep health app.log
   - **grep -v health app.log** (answer)
   - grep -c health app.log
   Why: -v inverts the match. -c would only print how many lines contain the word.

3. In the access log, what does awk '$9 >= 500 {print $7}' print?
   - **The path of every request that failed with a 5xx status** (answer)
   - Lines 9 to 500
   - The 500th field
   Why: awk splits each line on spaces. In this log format, field 9 is the status code and field 7 the path. The pattern before the braces filters rows.

4. You run sed -i 's/8080/9090/' app.conf on a server and it changes the wrong lines. How could you have been safe?
   - **Use sed -i.bak, which keeps app.conf.bak, and run it without -i first to preview** (answer)
   - Run it with sudo
   - There is no way to undo sed
   Why: Without -i, sed prints the result and changes nothing, so you can check it. -i.bak edits in place and keeps the original next to it.

5. Your pipeline grep ERROR app.log | wc -l should both count the errors and save them to errors.log. What goes in the middle?
   - > errors.log
   - **tee errors.log** (answer)
   - xargs
   Why: tee writes its input to a file and passes it on unchanged. A > redirect would send everything to the file and leave nothing for wc.

## Resources

- [GNU grep manual](https://www.gnu.org/software/grep/manual/grep.html) (GNU)
- [The GNU Awk user's guide](https://www.gnu.org/software/gawk/manual/gawk.html) (GNU)
- [sed(1) manual](https://manpages.ubuntu.com/manpages/noble/man1/sed.1.html) (Ubuntu manpages)
- [sort(1) manual](https://manpages.ubuntu.com/manpages/noble/man1/sort.1.html) (Ubuntu manpages)
- [LPIC-1 exam 101, objectives 103.2 and 103.7](https://www.lpi.org/our-certifications/exam-101-objectives/) (Linux Professional Institute)
- [regex101, test a regular expression with an explanation](https://regex101.com/) (regex101)
