Slicing and Counting: cut, sort, uniq, tr
The small tools you chain together every day: cut to take columns, sort to order lines by any column, uniq to count and find duplicates, tr to transform characters, plus wc, column and paste. With the classic pipelines that answer real questions about users, logs and data.
Why these tools matter
Logs, CSV exports, /etc/passwd, the output of ps, df or kubectl get pods: a huge amount of what you deal with as a DevOps engineer is text arranged in columns. Four small programs let you slice and count it without writing code:
| Tool | Does one thing |
|---|---|
cut | take out columns |
sort | order lines |
uniq | merge, count or find repeated lines |
tr | change, delete or squeeze characters |
Each is simple. Their power comes from combining them with pipes, which you learned in the redirection lesson.
cut: take out columns
cut works in two ways: by field (with a delimiter) or by character position.
| Command | Takes |
|---|---|
cut -d: -f1 | field 1, fields separated by : |
cut -d, -f2,4 | fields 2 and 4 of a CSV |
cut -d, -f2- | field 2 to the end |
cut -f3 | field 3, separated by tabs (the default delimiter) |
cut -c1-8 | characters 1 to 8 of every line |
cut -d: -f1 --complement | every field except field 1 |
/etc/passwd, field by field
/etc/passwd is the perfect example: one account per line, seven fields separated by colons.
The fields of /etc/passwd
asha:x:1000:1000::/home/asha:/bin/bash
cut -d: -f1,7 /etc/passwd | tail -4| Part | Meaning |
|---|---|
-d: | fields are separated by : |
-f1,7 | keep fields 1 (name) and 7 (shell) |
asha:/bin/bash
vikram:/bin/bash
meera:/bin/bash
backup-bot:/usr/sbin/nologinThree people who can log in with bash, and a system account (backup-bot) whose shell nologin prevents interactive logins. cut joins the chosen fields with the same delimiter.
cut's big limitation
cut treats every single delimiter character as a separator. Output that lines up columns with several spaces (like ps, df, ls -l or most tables) breaks it:
$ cut -d' ' -f2 servers.txt
(empty lines)Field 2 is the empty text between two neighbouring spaces. Two fixes:
tr -s ' ' < servers.txt | cut -d' ' -f2 # squeeze repeated spaces first
awk '{print $2}' servers.txt # awk splits on runs of whitespace by defaultAs a rule: cut for files with one clean separator (: , tab); awk for space-aligned output.
Columns with cut
List the user accounts whose login shell is /bin/bash.
cut splits each line at a delimiter (-d) and keeps the fields you ask for (-f). Fields are numbered from 1. It's perfect for files with a single, consistent separator, like /etc/passwd (:) or CSV files (,).
1. Look at /etc/passwd
tail -n 4 /etc/passwdasha:x:1000:1000::/home/asha:/bin/bash
vikram:x:1001:1001::/home/vikram:/bin/bash
meera:x:1002:1002::/home/meera:/bin/bash
backup-bot:x:997:996::/home/backup-bot:/usr/sbin/nologinSeven fields separated by :: 1 user name, 2 x (password stored elsewhere), 3 user ID, 4 group ID, 5 description (empty here), 6 home folder, 7 login shell. /usr/sbin/nologin means the account can't log in interactively.
2. Take columns with cut
cut -d: -f1 /etc/passwd | tail -4
cut -d: -f1,7 /etc/passwd | tail -4| Part | Meaning |
|---|---|
-d: | the delimiter is : |
-f1 | keep field 1 |
-f1,7 | keep fields 1 and 7 (ranges like -f1-3 also work) |
asha
vikram
meera
backup-bot
asha:/bin/bash
vikram:/bin/bash
meera:/bin/bash
backup-bot:/usr/sbin/nologinWith several fields, cut joins them with the same delimiter.
3. The gotcha: repeated spaces
cut -d' ' -f2 /srv/data/servers.txt
tr -s ' ' < /srv/data/servers.txt | cut -d' ' -f2(four empty lines)
10.0.1.11
10.0.1.12
10.0.2.21
10.0.3.31servers.txt lines up its columns with several spaces. cut treats every single space as a separator, so field 2 is the empty text between the first two spaces. tr -s ' ' squeezes runs of spaces into one, and then cut works. (awk '{print $2}' handles this automatically; you'll meet it soon.)
Save the user names of all accounts whose login shell is exactly /bin/bash to /root/bash-users.txt, one per line.
Expected result: /root/bash-users.txt lists root and the three human users, but not system accounts like backup-bot.
Hint: the commands, explained
grep can keep the lines that end in /bin/bash (anchor with $), and cut can take the first field:
grep '/bin/bash$' /etc/passwd | cut -d: -f1 > /root/bash-users.txtWhat each part does
grep '/bin/bash$' /etc/passwd: lines that end ($) with/bin/bash: users whose shell is bash.cut -d: -f1: split at:and keep field 1, the user name.
sort: put lines in order
By default, sort orders whole lines as text, character by character.
| Option | Effect |
|---|---|
-n | numeric: compare numbers by value |
-r | reverse the order |
-k N | sort by field N (fields separated by whitespace) |
-t, | use , as the field separator (for -k) |
-u | keep only one of identical lines |
-h | human sizes: understands 512K, 83M, 2.1G |
-f | ignore upper/lower case |
-V | version order: v1.9 before v1.10 |
-o file | write the result to a file (safe even if it's the input file) |
Text versus numbers
sort -t, -k4 sales.csv | head -4
tail -n +2 sales.csv | sort -t, -k4 -nr | head -3east,laptop,15,1050000
south,phone,40,1200000
north,tablet,11,165000
east,tablet,25,375000south,phone,40,1200000
east,laptop,15,1050000
west,phone,31,930000The first, text-sorted result is nonsense for money: 1050000 comes before 165000 because the second character 0 sorts before 6. With -n (numeric) and -r (largest first), and tail -n +2 to keep the header out of the way, you get the real ranking.
Sorting numbers without -n. It's the most common sort mistake, and it doesn't produce an error, just a wrong answer that looks plausible. Whenever a column holds numbers, add -n (or -h for sizes like 2G).
Sorting by several keys
-k can take a range and its own options. -k1,1 means "field 1 only" (without ,1 it would mean "from field 1 to the end of the line"):
sort -t, -k1,1 -k4,4nr sales.csv # by region A-Z, then by revenue, highest first, within each regionEveryday sorts
du -sh /var/* | sort -h # folders by size, biggest last
ls -l | sort -k5 -n # files by size (5th column)
sort -u emails.txt # sorted, without duplicates
sort -V versions.txt # 1.2, 1.9, 1.10 in the right orderSorting
Order the sales rows by revenue, highest first.
sort orders lines as text by default, character by character. That's wrong for numbers: as text, 1050000 comes before 165000 because 0 sorts before 6. For numbers you need -n. And to sort by a particular column, tell it the separator (-t) and the key (-k).
1. Sorting by a column, as text
sort -t, -k4 /srv/data/sales.csv | head -4| Part | Meaning |
|---|---|
-t, | fields are separated by commas |
-k4 | sort by the 4th field (the revenue) |
east,laptop,15,1050000
south,phone,40,1200000
north,tablet,11,165000
east,tablet,25,375000Not in numeric order: 1050000 and 1200000 come first because they start with 1, before 165000. Text sorting compares one character at a time.
2. Numerically, and highest first
tail -n +2 /srv/data/sales.csv | sort -t, -k4 -nr | head -3| Part | Meaning |
|---|---|
tail -n +2 | skip line 1, the header, so it doesn't get sorted in with the data |
-n | compare as numbers |
-r | reverse: largest first |
south,phone,40,1200000
east,laptop,15,1050000
west,phone,31,930000Correct: south's phone sales lead with 12 lakh.
3. Other options you'll use
| Option | Effect |
|---|---|
-u | output each line only once (unique) |
-h | human sizes: understands 4K, 83M, 2G. Use it with du -sh * | sort -h. |
-k1,1 -k4,4nr | sort by field 1, then by field 4 numerically in reverse within each group |
-f | ignore case |
Save the sales rows (without the header line) sorted by revenue, highest first, to /root/sales-by-revenue.txt.
Expected result: the file has 9 lines, starting with the south,phone row and ending with north,tablet.
Hint: the commands, explained
tail -n +2 /srv/data/sales.csv | sort -t, -k4 -nr > /root/sales-by-revenue.txtWhat each part does
tail -n +2 FILE: print from line 2 onward, skipping the CSV header.sort -t, -k4 -nr: fields are separated by commas (-t,); sort by the 4th field (-k4), as numbers, in reverse (highest revenue first).
uniq: repeated lines
uniq collapses identical neighbouring lines into one. Because it only compares a line with the one directly above it, you almost always sort first.
| Option | Prints |
|---|---|
| (none) | each distinct line once |
-c | a count in front of each distinct line |
-d | only lines that appear more than once |
-u | only lines that appear exactly once |
-i | compare ignoring case |
cut -d, -f2 sales.csv | tail -n +2 | uniq -c
cut -d, -f2 sales.csv | tail -n +2 | sort | uniq -c 1 laptop
1 phone
1 laptop
1 tablet
... 4 laptop
3 phone
2 tabletWithout sorting, identical products that aren't next to each other are counted separately. Sorted, the counts are right.
The "top N" pipeline
This pipeline is worth memorising. It answers "what are the most common X?" for anything:
... | sort | uniq -c | sort -rn | head -10| Stage | Does |
|---|---|
... | produce one item per line (IPs, error messages, user names, status codes) |
sort | group identical items |
uniq -c | count each group |
sort -rn | most frequent first |
head -10 | the top 10 |
cut -d' ' -f1 access.log | sort | uniq -c | sort -rn | head # busiest client IPs
grep -o 'reason=[a-z_]*' app.log | sort | uniq -c | sort -rn # most common failure reasons
cut -d: -f7 /etc/passwd | sort | uniq -c # how many accounts use each shelltr: change characters
tr (translate) works on characters, not words or lines. It reads only standard input, so you feed it with < or a pipe.
| Command | Effect |
|---|---|
tr 'a-z' 'A-Z' | lowercase to uppercase (each character of set 1 becomes the matching character of set 2) |
tr ',' '\n' | commas to newlines |
tr -d '\r' | delete carriage returns (fixes Windows line endings) |
tr -d '0-9' | delete all digits |
tr -dc 'a-zA-Z0-9' | delete everything except letters and digits (-c = complement) |
tr -s ' ' | squeeze runs of spaces into one |
tr '[:lower:]' '[:upper:]' | the same as a-z A-Z, using character classes |
tr 'A-Z' 'a-z' < signups.txt | sort -u
echo $PATH | tr ':' '\n'/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/binEight signups with different capitalisation became five real people once everything was lowercased. And PATH becomes readable with each folder on its own line.
Normalise before you compare. Lowercase emails, strip spaces, remove \r from Windows files, and only then sort and uniq. Most "why are my duplicates not detected?" problems come from invisible differences in case or whitespace.
Cleaning with tr
Turn the messy signup list into a clean, lowercase list of unique emails.
tr (translate) changes characters one by one. It reads only from stdin (use < or a pipe; it doesn't take file names) and has three modes:
| Command | Effect |
|---|---|
tr 'A-Z' 'a-z' | replace each character of the first set with the matching one in the second: upper to lower case |
tr -d '0-9' | delete these characters |
tr -s ' ' | squeeze repeats into a single character |
1. The messy list
sort /srv/data/signups.txt[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]Eight lines, but [email protected] and [email protected] are the same person. Emails aren't case-sensitive, but sort and uniq are, so they can't see the duplicates yet. (Capitals sort before lowercase here.)
2. Lowercase everything first
tr 'A-Z' 'a-z' < /srv/data/signups.txt | sort -u| Part | Meaning |
|---|---|
tr 'A-Z' 'a-z' | every capital letter becomes lowercase |
< /srv/data/signups.txt | feed the file in on stdin |
sort -u | sort, and keep each line once |
Five real people. Normalising before comparing is the trick behind almost every de-duplication job.
3. More tr tricks
echo $PATH | tr ':' '\n'
echo "phone: +91-98450-11111" | tr -d -c '0-9\n'| Command | Effect |
|---|---|
tr ':' '\n' | each : becomes a newline, so the PATH folders appear one per line |
tr -d -c '0-9\n' | delete (-d) everything except (-c, complement) digits and newlines |
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin
919845011111Create /root/clean-emails.txt: the signup emails in lowercase, sorted, each email once.
Expected result: 5 lines, all lowercase, no duplicates.
Hint: the commands, explained
tr 'A-Z' 'a-z' < /srv/data/signups.txt | sort -u > /root/clean-emails.txtWhat each part does
tr 'A-Z' 'a-z' < FILE: translate every uppercase letter to lowercase, so[email protected]and[email protected]become identical.<feeds the file in.sort -u: sort and keep each line once (unique).
Duplicates with uniq
Find the people who signed up more than once.
uniq collapses repeated neighbouring lines into one. It only compares each line with the one right before it, so always sort first. Its options turn it into a counting tool:
| Option | Prints |
|---|---|
| (none) | each distinct line once |
-c | each distinct line with a count in front |
-d | only lines that appear more than once (duplicates) |
-u | only lines that appear exactly once (unique) |
-i | ignore case when comparing |
1. Why sort first
cut -d, -f2 /srv/data/sales.csv | tail -n +2 | uniq -c | head -4
cut -d, -f2 /srv/data/sales.csv | tail -n +2 | sort | uniq -c 1 laptop
1 phone
1 laptop
1 tablet 4 laptop
3 phone
2 tabletWithout sort, laptop appears several times with a count of 1: the same products weren't next to each other. Sorted, the counts are right: 4 laptop rows, 3 phone rows, 2 tablet rows.
2. Counts and duplicates in the signups
tr 'A-Z' 'a-z' < /srv/data/signups.txt | sort | uniq -c | sort -rnThree people signed up twice. sort | uniq -c | sort -rn is the classic "how many of each, most frequent first" pipeline: top IPs in an access log, most common errors, busiest users.
Save the emails that appear more than once in the signup list (comparing case-insensitively), in lowercase, one per line, to /root/duplicate-signups.txt.
Expected result: the file contains exactly the three duplicated emails, in lowercase.
Hint: the commands, explained
tr 'A-Z' 'a-z' < /srv/data/signups.txt | sort | uniq -d > /root/duplicate-signups.txtWhat each part does
- Same lowercase step, then
sortso duplicates sit next to each other. uniq -d: print only lines that appear more than once (one copy of each).uniqonly compares neighbouring lines, which is whysortcomes first.
A few more helpers
| Command | Does | Example |
|---|---|---|
wc -l | count lines | grep ERROR app.log | wc -l |
column -t | align columns into a readable table | column -t -s, sales.csv |
paste | join files side by side, line by line | paste -d, names.txt shells.txt |
rev | reverse each line's characters | handy for taking the last field: rev | cut -d/ -f1 | rev |
nl | number lines | nl script.sh |
comm | compare two sorted files: lines only in A, only in B, in both | comm -12 a.txt b.txt (lines in both) |
column -t -s, sales.csv | head -4region product units revenue
north laptop 12 840000
south phone 40 1200000
west laptop 7 490000-s, tells column the input is comma-separated; -t builds a table. Great for reading CSV files in the terminal.
"How do you find the 10 most frequent IP addresses in an access log?" awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -10 (or cut -d' ' -f1 instead of awk).
"How do you list all users that have bash as their shell?" grep '/bin/bash$' /etc/passwd | cut -d: -f1, or awk -F: '$7=="/bin/bash"{print $1}' /etc/passwd.
"What's the difference between sort -u and uniq?" sort -u sorts and removes duplicates in one step. uniq only removes adjacent duplicates, and adds options like -c (count) and -d (duplicates only).
Summary
cut -d DELIM -f FIELDSfor cleanly delimited files;-cfor character positions. Squeeze spaces withtr -s ' 'or use awk for space-aligned output.sortis text-based by default:-nnumbers,-rreverse,-t, -k4a column,-hsizes,-uunique,-Vversions.uniqneeds sorted input:-ccount,-dduplicates,-usingles.trmaps, deletes (-d) or squeezes (-s) characters; it reads stdin only.- The top-N pipeline:
... | sort | uniq -c | sort -rn | head. column -t,paste,comm,nl,revround out the toolbox.
Quick quiz
You've practised everything in this lesson
Every task was checked on your own machine. You can end the lab, or keep experimenting in the terminal.