Learn / Linux / Text Processing
Lesson 12 of 74

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.

25 min read Report a problem Hands-on lab included 5-question quiz

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:

ToolDoes one thing
cuttake out columns
sortorder lines
uniqmerge, count or find repeated lines
trchange, 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.

CommandTakes
cut -d: -f1field 1, fields separated by :
cut -d, -f2,4fields 2 and 4 of a CSV
cut -d, -f2-field 2 to the end
cut -f3field 3, separated by tabs (the default delimiter)
cut -c1-8characters 1 to 8 of every line
cut -d: -f1 --complementevery 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

asha1 · user name
x2 · password (stored in /etc/shadow)
10003 · user ID (UID)
10004 · group ID (GID)
 5 · description (empty)
/home/asha6 · home folder
/bin/bash7 · login shell

asha:x:1000:1000::/home/asha:/bin/bash

bash
cut -d: -f1,7 /etc/passwd | tail -4
PartMeaning
-d:fields are separated by :
-f1,7keep fields 1 (name) and 7 (shell)
text
asha:/bin/bash
vikram:/bin/bash
meera:/bin/bash
backup-bot:/usr/sbin/nologin

Three 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:

text
$ cut -d' ' -f2 servers.txt
(empty lines)

Field 2 is the empty text between two neighbouring spaces. Two fixes:

text
tr -s ' ' < servers.txt | cut -d' ' -f2     # squeeze repeated spaces first
awk '{print $2}' servers.txt                 # awk splits on runs of whitespace by default

As a rule: cut for files with one clean separator (: , tab); awk for space-aligned output.

Try it · Task 1 of 4

Columns with cut

List the user accounts whose login shell is /bin/bash.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

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

bash
tail -n 4 /etc/passwd
text
asha: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/nologin

Seven 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

bash
cut -d: -f1 /etc/passwd | tail -4
cut -d: -f1,7 /etc/passwd | tail -4
PartMeaning
-d:the delimiter is :
-f1keep field 1
-f1,7keep fields 1 and 7 (ranges like -f1-3 also work)
text
asha
vikram
meera
backup-bot
asha:/bin/bash
vikram:/bin/bash
meera:/bin/bash
backup-bot:/usr/sbin/nologin

With several fields, cut joins them with the same delimiter.

3. The gotcha: repeated spaces

bash
cut -d' ' -f2 /srv/data/servers.txt
tr -s ' ' < /srv/data/servers.txt | cut -d' ' -f2
text
(four empty lines)
10.0.1.11
10.0.1.12
10.0.2.21
10.0.3.31

servers.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.)

2 · Your task

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:

text
grep '/bin/bash$' /etc/passwd | cut -d: -f1 > /root/bash-users.txt

What 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.
First start the lab machine in the terminal panel on the right.

sort: put lines in order

By default, sort orders whole lines as text, character by character.

OptionEffect
-nnumeric: compare numbers by value
-rreverse the order
-k Nsort by field N (fields separated by whitespace)
-t,use , as the field separator (for -k)
-ukeep only one of identical lines
-hhuman sizes: understands 512K, 83M, 2.1G
-fignore upper/lower case
-Vversion order: v1.9 before v1.10
-o filewrite the result to a file (safe even if it's the input file)

Text versus numbers

bash
sort -t, -k4 sales.csv | head -4
tail -n +2 sales.csv | sort -t, -k4 -nr | head -3
text
east,laptop,15,1050000
south,phone,40,1200000
north,tablet,11,165000
east,tablet,25,375000
text
south,phone,40,1200000
east,laptop,15,1050000
west,phone,31,930000

The 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"):

text
sort -t, -k1,1 -k4,4nr sales.csv     # by region A-Z, then by revenue, highest first, within each region

Everyday sorts

text
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 order
Try it · Task 2 of 4

Sorting

Order the sales rows by revenue, highest first.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

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

bash
sort -t, -k4 /srv/data/sales.csv | head -4
PartMeaning
-t,fields are separated by commas
-k4sort by the 4th field (the revenue)
text
east,laptop,15,1050000
south,phone,40,1200000
north,tablet,11,165000
east,tablet,25,375000

Not 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

bash
tail -n +2 /srv/data/sales.csv | sort -t, -k4 -nr | head -3
PartMeaning
tail -n +2skip line 1, the header, so it doesn't get sorted in with the data
-ncompare as numbers
-rreverse: largest first
text
south,phone,40,1200000
east,laptop,15,1050000
west,phone,31,930000

Correct: south's phone sales lead with 12 lakh.

3. Other options you'll use

OptionEffect
-uoutput each line only once (unique)
-hhuman sizes: understands 4K, 83M, 2G. Use it with du -sh * | sort -h.
-k1,1 -k4,4nrsort by field 1, then by field 4 numerically in reverse within each group
-fignore case
2 · Your task

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
text
tail -n +2 /srv/data/sales.csv | sort -t, -k4 -nr > /root/sales-by-revenue.txt

What 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).
First start the lab machine in the terminal panel on the right.

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.

OptionPrints
(none)each distinct line once
-ca count in front of each distinct line
-donly lines that appear more than once
-uonly lines that appear exactly once
-icompare ignoring case
bash
cut -d, -f2 sales.csv | tail -n +2 | uniq -c
cut -d, -f2 sales.csv | tail -n +2 | sort | uniq -c
text
      1 laptop
      1 phone
      1 laptop
      1 tablet
      ...
text
      4 laptop
      3 phone
      2 tablet

Without 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:

text
... | sort | uniq -c | sort -rn | head -10
StageDoes
...produce one item per line (IPs, error messages, user names, status codes)
sortgroup identical items
uniq -ccount each group
sort -rnmost frequent first
head -10the top 10
text
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 shell

tr: change characters

tr (translate) works on characters, not words or lines. It reads only standard input, so you feed it with < or a pipe.

CommandEffect
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
bash
tr 'A-Z' 'a-z' < signups.txt | sort -u
echo $PATH | tr ':' '\n'
text
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin

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

Try it · Task 3 of 4

Cleaning with tr

Turn the messy signup list into a clean, lowercase list of unique emails.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

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:

CommandEffect
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

bash
sort /srv/data/signups.txt

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

bash
tr 'A-Z' 'a-z' < /srv/data/signups.txt | sort -u
PartMeaning
tr 'A-Z' 'a-z'every capital letter becomes lowercase
< /srv/data/signups.txtfeed the file in on stdin
sort -usort, and keep each line once

Five real people. Normalising before comparing is the trick behind almost every de-duplication job.

3. More tr tricks

bash
echo $PATH | tr ':' '\n'
echo "phone: +91-98450-11111" | tr -d -c '0-9\n'
CommandEffect
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
text
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin
919845011111
2 · Your task

Create /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
text
tr 'A-Z' 'a-z' < /srv/data/signups.txt | sort -u > /root/clean-emails.txt

What 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).
First start the lab machine in the terminal panel on the right.
Try it · Task 4 of 4

Duplicates with uniq

Find the people who signed up more than once.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

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:

OptionPrints
(none)each distinct line once
-ceach distinct line with a count in front
-donly lines that appear more than once (duplicates)
-uonly lines that appear exactly once (unique)
-iignore case when comparing

1. Why sort first

bash
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
text
      1 laptop
      1 phone
      1 laptop
      1 tablet
text
      4 laptop
      3 phone
      2 tablet

Without 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

bash
tr 'A-Z' 'a-z' < /srv/data/signups.txt | sort | uniq -c | sort -rn

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

2 · Your task

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
text
tr 'A-Z' 'a-z' < /srv/data/signups.txt | sort | uniq -d > /root/duplicate-signups.txt

What each part does

  • Same lowercase step, then sort so duplicates sit next to each other.
  • uniq -d: print only lines that appear more than once (one copy of each). uniq only compares neighbouring lines, which is why sort comes first.
First start the lab machine in the terminal panel on the right.

A few more helpers

CommandDoesExample
wc -lcount linesgrep ERROR app.log | wc -l
column -talign columns into a readable tablecolumn -t -s, sales.csv
pastejoin files side by side, line by linepaste -d, names.txt shells.txt
revreverse each line's charactershandy for taking the last field: rev | cut -d/ -f1 | rev
nlnumber linesnl script.sh
commcompare two sorted files: lines only in A, only in B, in bothcomm -12 a.txt b.txt (lines in both)
bash
column -t -s, sales.csv | head -4
text
region  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 FIELDS for cleanly delimited files; -c for character positions. Squeeze spaces with tr -s ' ' or use awk for space-aligned output.
  • sort is text-based by default: -n numbers, -r reverse, -t, -k4 a column, -h sizes, -u unique, -V versions.
  • uniq needs sorted input: -c count, -d duplicates, -u singles.
  • tr maps, 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, rev round out the toolbox.
Check your understanding

Quick quiz

Feedback