Menu
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.”
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:
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.csvLooking at files: cat, less, nl#
cat (concatenate) prints files one after the other. With one file, it simply shows it:
cat -n fruits.txt 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:
printf 'one\n\nthree\n' | nl 1 one
2 threeThe start and the end: head and tail#
head prints the first 10 lines, tail the last 10. Change the number with -n:
head -n 2 fruits.txt
tail -n 2 fruits.txtbanana
apple
banana
appleUseful 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+Cstops.tail -F file: follow, and keep going if the file is rotated (replaced by a new one).head -2is the old short form ofhead -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:
wc fruits.txt
wc -l fruits.txt
wc -l < fruits.txt 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:
sort fruits.txtapple
apple
apple
banana
banana
cherryNumbers need -n, or 10 comes before 9 (it compares character by character):
printf '10\n9\n100\n' | sort
printf '10\n9\n100\n' | sort -n10
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:
tail -n +2 staff.csv | sort -t, -k4 -nr1,Tom,dev,5100
2,Lin,dev,4800
3,Sara,ops,4200
4,Joe,ops,3900Removing duplicates: uniq#
uniq removes duplicate lines, but only when they’re next to each other. That’s why you almost always sort first:
uniq fruits.txt | tr '\n' ' '
sort fruits.txt | uniq -cbanana 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:
cut -d, -f2 staff.csv
cut -d: -f1,7 /etc/passwd | head -3
cut -c1-3 fruits.txt | head -2name
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.
printf 'Tom\nLin\nSara\n' > names
printf 'dev\ndev\nops\n' > teams
paste names teams
paste -d, names teams
paste -s -d, namesTom dev
Lin dev
Sara ops
Tom,dev
Lin,dev
Sara,ops
Tom,Lin,SaraThe 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:
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 -2HELLO WORLD
hello world
hello
5551234
id name dept salary
3 Sara ops 4200tr 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, but these four forms cover most filter jobs:
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 matchThe last one leaves only the lines without “apple”:
banana
cherry
bananased 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:
echo "Hi!" | od -c
echo "Hi!" | od -t x1 -c0000000 H i ! \n
0000004
0000000 48 69 21 0a
H i ! \n
0000004The 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:
seq 1 10 > nums
split -l 4 nums part_
ls part_*
cat part_* > joinedpart_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:
echo "hello" > greet.txt
md5sum greet.txt
sha256sum greet.txtb1946ac92492d2347c6235b4d2611184 greet.txt
5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03 greet.txtSave the hashes to a file and check them later with -c:
sha256sum greet.txt > greet.sha256
sha256sum -c greet.sha256
echo "changed" >> greet.txt
sha256sum -c greet.sha256greet.txt: OK
greet.txt: FAILED
sha256sum: WARNING: 1 computed checksum did NOT matchLinux 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 |
zcat /var/log/syslog.2.gz | grep -c error
xzcat backup.sql.xz | headzless 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?
cut -d: -f7 /etc/passwd | sort | uniq -c | sort -nr 31 /usr/sbin/nologin
2 /bin/bash
1 /bin/synccut 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). uniqonly removes adjacent duplicates:sort | uniq.uniq -ccounts,-dshows duplicates,-ushows unique lines.sort -nnumeric,-rreverse,-kfield,-tseparator,-uunique,-hhuman sizes.cut -d: -f1picks fields (default delimiter is a tab),cut -c1-5picks characters.pastejoins files side by side;paste -sjoins lines.tronly reads standard input.-ddelete,-ssqueeze,-ccomplement;tr 'a-z' 'A-Z'uppercases.head/taildefault to 10 lines.tail -ffollows a log,tail -n +2starts at line 2.wc -llines,-wwords,-cbytes.nlnumbers non-empty lines;cat -nnumbers all,cat -Ashows tabs and line ends.od -cshows raw characters,split -l/-bcuts files (default prefixx, 1000 lines),cat x*rejoins.md5sum,sha256sum,sha512summake checksums;-cverifies a list.zcat,bzcat,xzcatprint compressed files.
Answer these 3 questions to commit this byte to your learning path.
Reset. This byte isn't committed any more. Answer the questions again to commit it.
$ git commit -m "learn(lpic-103): Process text streams using filters"
[main ef233c6] learn(lpic-103): Process text streams using filters
1 byte changed, 3 insertions(+)
See it on your path Already committed . Try the questions again any time, it won't undo anything. To uncommit it and start over: