# Process text streams using filters

> cat, head, tail, sort, uniq, cut, paste, tr, wc, nl, od, split, sed and checksums: small tools that reshape text.

Source: https://aminbytes.dev/bytes/gnu-and-unix-commands/text-filters/


Linux is full of text: config files, logs, command output, CSV exports. Instead of one big program that does everything, you get many small **filters**. A filter reads text (from files or from standard input), changes it in one simple way, and writes the result to standard output. Chain a few of them with a pipe `|` and you can answer questions like "which IP hit my server most often?" in one line.

Most of these tools come from GNU **coreutils** (it used to be a separate package called textutils), so they're on every Linux system. None of them change the original file unless you ask: they print a new version.

## Sample files

Make two small files to practice on:

```bash
printf '%s\n' banana apple cherry apple banana apple > fruits.txt
printf '%s\n' id,name,dept,salary 3,Sara,ops,4200 1,Tom,dev,5100 2,Lin,dev,4800 4,Joe,ops,3900 > staff.csv
```

## Looking at files: cat, less, nl

`cat` (concatenate) prints files one after the other. With one file, it simply shows it:

```bash
cat -n fruits.txt
```

```text
     1	banana
     2	apple
     3	cherry
     4	apple
     5	banana
     6	apple
```

| Option | Meaning |
| --- | --- |
| `-n` | Number all lines |
| `-b` | Number only non-empty lines |
| `-s` | Squeeze several empty lines into one |
| `-A` | Show hidden characters: tabs as `^I`, line ends as `$` |

`cat -A` is how you find a stray tab or a trailing space. `cat part1 part2 > whole` joins files.

`less` is a **pager**: it shows a long file one screen at a time and lets you move around. It doesn't load the whole file first, so it opens huge logs instantly.

| Key in `less` | Action |
| --- | --- |
| `Space` / `b` | Next page / previous page |
| `g` / `G` | Start / end of the file |
| `/text` / `?text` | Search forward / backward |
| `n` / `N` | Next / previous match |
| `q` | Quit |

`less -N` shows line numbers. `man` uses `less` to show manual pages, so the same keys work there.

`nl` (number lines) is a more flexible `cat -n`. By default it numbers only non-empty lines (`-b t`); `-b a` numbers all of them:

```bash
printf 'one\n\nthree\n' | nl
```

```text
     1	one
       
     2	three
```

## The start and the end: head and tail

`head` prints the first 10 lines, `tail` the last 10. Change the number with `-n`:

```bash
head -n 2 fruits.txt
tail -n 2 fruits.txt
```

```text
banana
apple
banana
apple
```

Useful variants:

- `head -c 5 file`: the first 5 **bytes** instead of lines.
- `tail -n +2 file`: everything **from line 2** on. Perfect for skipping a header line.
- `tail -f /var/log/syslog`: **follow** the file and print new lines as they're written. `Ctrl+C` stops.
- `tail -F file`: follow, and keep going if the file is rotated (replaced by a new one).
- `head -2` is the old short form of `head -n 2`, and you'll still see it everywhere.

To get line 5 only, combine them: `head -n 5 file | tail -n 1`.

## Counting: wc

`wc` (word count) prints lines, words and bytes:

```bash
wc fruits.txt
wc -l fruits.txt
wc -l < fruits.txt
```

```text
 6  6 39 fruits.txt
6 fruits.txt
6
```

`-l` lines, `-w` words, `-c` bytes, `-m` characters (differs from bytes for UTF-8 text). Reading from standard input with `<` leaves out the file name, which is nicer in scripts.

## Sorting: sort

`sort` sorts lines alphabetically:

```bash
sort fruits.txt
```

```text
apple
apple
apple
banana
banana
cherry
```

Numbers need `-n`, or `10` comes before `9` (it compares character by character):

```bash
printf '10\n9\n100\n' | sort
printf '10\n9\n100\n' | sort -n
```

```text
10
100
9
9
10
100
```

| Option | Meaning |
| --- | --- |
| `-n` | Numeric sort |
| `-h` | Human sizes: `1K < 512M < 2G` |
| `-r` | Reverse order |
| `-u` | Unique: drop duplicate lines |
| `-f` | Ignore case |
| `-t,` | Field separator (here a comma; default is whitespace) |
| `-k3` | Sort by field 3 (`-k3,3` means *only* field 3) |
| `-o file` | Write the result to a file (can be the input file) |

Sort the staff by salary, highest first, skipping the header:

```bash
tail -n +2 staff.csv | sort -t, -k4 -nr
```

```text
1,Tom,dev,5100
2,Lin,dev,4800
3,Sara,ops,4200
4,Joe,ops,3900
```

## Removing duplicates: uniq

`uniq` removes duplicate lines, but **only when they're next to each other**. That's why you almost always sort first:

```bash
uniq fruits.txt | tr '\n' ' '
sort fruits.txt | uniq -c
```

```text
banana apple cherry apple banana apple 
      3 apple
      2 banana
      1 cherry
```

| Option | Meaning |
| --- | --- |
| `-c` | Count how many times each line appears |
| `-d` | Print only lines that are duplicated |
| `-u` | Print only lines that appear once |
| `-i` | Ignore case |

## Picking columns: cut

`cut` takes parts of each line, either by field or by character position:

```bash
cut -d, -f2 staff.csv
cut -d: -f1,7 /etc/passwd | head -3
cut -c1-3 fruits.txt | head -2
```

```text
name
Sara
Tom
Lin
Joe
root:/bin/bash
daemon:/usr/sbin/nologin
bin:/usr/sbin/nologin
ban
app
```

`-d` sets the delimiter (one character; the default is a tab), `-f` picks fields (`2`, `1,7`, `2-4`, `3-`), and `-c` picks characters. `cut` can't split on "any amount of spaces", so for space-aligned output, squeeze the spaces first with `tr -s ' '`.

## Joining columns: paste

`paste` is the opposite of `cut`: it puts lines from several files side by side.

```bash
printf 'Tom\nLin\nSara\n' > names
printf 'dev\ndev\nops\n' > teams
paste names teams
paste -d, names teams
paste -s -d, names
```

```text
Tom	dev
Lin	dev
Sara	ops
Tom,dev
Lin,dev
Sara,ops
Tom,Lin,Sara
```

The default separator is a tab; `-d` changes it. `-s` (serial) joins all lines of one file into a single line.

## Changing characters: tr

`tr` (translate) replaces or deletes **characters**. It only reads standard input, so you feed it with a pipe or `<`, never a file name:

```bash
echo "hello world" | tr 'a-z' 'A-Z'
echo "hello   world" | tr -s ' '
echo "h-e-l-l-o" | tr -d '-'
echo "phone: 555-1234" | tr -cd '0-9'; echo
tr ',' '\t' < staff.csv | head -2
```

```text
HELLO WORLD
hello world
hello
5551234
id	name	dept	salary
3	Sara	ops	4200
```

`tr SET1 SET2` maps each character of the first set to the one at the same position in the second. `-d` deletes the characters in the set, `-s` squeezes repeats into one, and `-c` uses the **complement** (every character *not* in the set). Character classes work too: `tr '[:lower:]' '[:upper:]'`.

## Editing the stream: sed

`sed` (stream editor) changes text as it flows through. It gets its own deep dive in [regular expressions](../regular-expressions/), but these four forms cover most filter jobs:

```bash
sed 's/apple/APPLE/' fruits.txt   # substitute the first match on each line
sed 's/apple/APPLE/g' fruits.txt  # g: every match on the line
sed -n '2,3p' fruits.txt          # -n: print nothing except lines 2 to 3
sed '/apple/d' fruits.txt         # delete lines that match
```

The last one leaves only the lines without "apple":

```text
banana
cherry
banana
```

`sed` prints to the screen and leaves the file alone. `sed -i` edits the file in place.

## Looking at bytes: od

`od` (octal dump) shows the raw bytes of a file. It's how you see characters that don't print, like a Windows line ending (`\r`) breaking a script:

```bash
echo "Hi!" | od -c
echo "Hi!" | od -t x1 -c
```

```text
0000000   H   i   !  \n
0000004
0000000  48  69  21  0a
          H   i   !  \n
0000004
```

The number on the left is the offset, in octal by default (`-A d` for decimal, `-A x` for hex, `-A n` for none). `-c` shows characters, `-t x1` shows each byte in hex. Plain `od` with no options prints octal words, which is rarely what you want.

## Cutting files into pieces: split

`split` breaks a file into smaller files, by default 1000 lines each, named `xaa`, `xab` and so on:

```bash
seq 1 10 > nums
split -l 4 nums part_
ls part_*
cat part_* > joined
```

```text
part_aa  part_ab  part_ac
```

| Option | Meaning |
| --- | --- |
| `-l N` | N lines per piece |
| `-b SIZE` | SIZE bytes per piece (`-b 100M`) |
| `-n N` | Exactly N pieces of about equal size |
| `-d` | Numbers as suffixes (`part_00`) instead of letters |

The last argument is a **prefix** for the new files. Because the suffixes sort in order, `cat part_* > whole` puts the file back together.

## Checksums: md5sum, sha256sum, sha512sum

A checksum (hash) is a short fingerprint of a file's contents. Change one byte and the hash changes completely. Use it to check that a download or a copy is intact:

```bash
echo "hello" > greet.txt
md5sum greet.txt
sha256sum greet.txt
```

```text
b1946ac92492d2347c6235b4d2611184  greet.txt
5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03  greet.txt
```

Save the hashes to a file and check them later with `-c`:

```bash
sha256sum greet.txt > greet.sha256
sha256sum -c greet.sha256
echo "changed" >> greet.txt
sha256sum -c greet.sha256
```

```text
greet.txt: OK
greet.txt: FAILED
sha256sum: WARNING: 1 computed checksum did NOT match
```

Linux ISO downloads come with a `SHA256SUMS` file for exactly this. `sha512sum` works the same way with a longer hash.

> [!WARNING]
> MD5 is broken for security: people can craft two different files with the same MD5. It's still fine to catch accidental corruption, but use SHA-256 or SHA-512 when tampering matters.

## Compressed files: zcat, bzcat, xzcat

Logs in `/var/log` are often compressed after rotation (`syslog.2.gz`). These tools print the uncompressed content without creating a new file, so you can pipe it into other filters:

| Tool | Reads | Same as |
| --- | --- | --- |
| `zcat` | `.gz` (gzip) | `gunzip -c` |
| `bzcat` | `.bz2` (bzip2) | `bunzip2 -c` |
| `xzcat` | `.xz` (xz) | `unxz -c` |

```bash
zcat /var/log/syslog.2.gz | grep -c error
xzcat backup.sql.xz | head
```

 (Side note: There are more helpers in the same style: `zless` to page through a `.gz` file, and `zgrep`, `bzgrep` and `xzgrep` to search inside compressed files directly.)

On a minimal system, `bzcat` and `xzcat` may need the `bzip2` and `xz-utils` (Debian/Ubuntu) or `xz` (RHEL/Fedora) packages.

## Putting it together

Filters shine in pipelines. Which login shells are used on this system, and how often?

```bash
cut -d: -f7 /etc/passwd | sort | uniq -c | sort -nr
```

```text
     31 /usr/sbin/nologin
      2 /bin/bash
      1 /bin/sync
```

`cut` takes the shell field, `sort` groups identical lines, `uniq -c` counts them and `sort -nr` puts the biggest first. This "sort, uniq -c, sort -nr" pattern is worth memorizing: it's the answer to a lot of "what's most common?" questions.

## Exam checklist

- Filters read files or standard input and write to standard output. They don't change the original file (except `sed -i`).
- `uniq` only removes **adjacent** duplicates: `sort | uniq`. `uniq -c` counts, `-d` shows duplicates, `-u` shows unique lines.
- `sort -n` numeric, `-r` reverse, `-k` field, `-t` separator, `-u` unique, `-h` human sizes.
- `cut -d: -f1` picks fields (default delimiter is a tab), `cut -c1-5` picks characters. `paste` joins files side by side; `paste -s` joins lines.
- `tr` only reads standard input. `-d` delete, `-s` squeeze, `-c` complement; `tr 'a-z' 'A-Z'` uppercases.
- `head`/`tail` default to 10 lines. `tail -f` follows a log, `tail -n +2` starts at line 2.
- `wc -l` lines, `-w` words, `-c` bytes. `nl` numbers non-empty lines; `cat -n` numbers all, `cat -A` shows tabs and line ends.
- `od -c` shows raw characters, `split -l`/`-b` cuts files (default prefix `x`, 1000 lines), `cat x*` rejoins.
- `md5sum`, `sha256sum`, `sha512sum` make checksums; `-c` verifies a list. `zcat`, `bzcat`, `xzcat` print compressed files.


## Byte check

1. A file has the lines `b`, `a`, `b`, `a`. What does `uniq file` print?
   - `a` and `b`
   - **`b`, `a`, `b`, `a`** (correct)
   - `b` and `a`
   `uniq` only removes duplicates that sit on **adjacent** lines. None of these are next to each other, so nothing changes. Use `sort file | uniq` (or `sort -u`).

2. Which command prints the 2nd field of each line in a comma-separated file?
   - `cut -f2 data.csv`
   - **`cut -d, -f2 data.csv`** (correct)
   - `cut -c2 data.csv`
   `cut` splits on tabs by default. `-d,` sets the delimiter to a comma and `-f2` picks the second field. `-c2` would give the second character.

3. How do you follow a log file as new lines are written to it?
   - `head -f /var/log/syslog`
   - **`tail -f /var/log/syslog`** (correct)
   - `less -n /var/log/syslog`
   `tail -f` keeps the file open and prints new lines as they arrive. Press `Ctrl+C` to stop.


