Menu

GNU and Unix Commands

Step 2 of 8 LPIC-1 103.2weight 2

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.”

View .md

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
OptionMeaning
-nNumber all lines
-bNumber only non-empty lines
-sSqueeze several empty lines into one
-AShow 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 lessAction
Space / bNext page / previous page
g / GStart / end of the file
/text / ?textSearch forward / backward
n / NNext / previous match
qQuit

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
OptionMeaning
-nNumeric sort
-hHuman sizes: 1K < 512M < 2G
-rReverse order
-uUnique: drop duplicate lines
-fIgnore case
-t,Field separator (here a comma; default is whitespace)
-k3Sort by field 3 (-k3,3 means only field 3)
-o fileWrite 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
OptionMeaning
-cCount how many times each line appears
-dPrint only lines that are duplicated
-uPrint only lines that appear once
-iIgnore 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, 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
OptionMeaning
-l NN lines per piece
-b SIZESIZE bytes per piece (-b 100M)
-n NExactly N pieces of about equal size
-dNumbers 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:

ToolReadsSame 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
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

0/3

Answer these 3 questions to commit this byte to your learning path.

  1. A file has the lines b, a, b, a. What does uniq file print?
  2. Which command prints the 2nd field of each line in a comma-separated file?
  3. How do you follow a log file as new lines are written to it?
Search posts and bytes

Optional account

Keep your progress everywhere

Everything on AminBytes is free to read, with or without an account. Sign in only if you want your commits, streak and merged topics saved, on every device.

or

We keep only your name, avatar and which bytes you finished, and you can delete it all anytime. Privacy