Using cut, sort, uniq, and wc

Su Suriya Ravichandran Updated 06 Dec 2026
9 min read ·Lesson 107 of 205

cut, sort, uniq and wc are small GNU coreutils programs that each do one job with text: cut extracts parts of lines, sort orders lines, uniq collapses repeated lines, and wc counts lines, words and characters. None of them is a Bash built-in, but together they answer a large share of everyday questions about files and command output: which values appear, how often, in what order, and how many.

Like grep, sed and awk (lesson 106), these tools read files named on the command line or standard input, and write to standard output, so they combine naturally in pipelines.

The Sample Files

The examples use these files.

users.txt, in the colon-separated format of /etc/passwd (name, password placeholder, user id, group id, full name, home directory, login shell):

ana:x:1001:1001:Ana Silva:/home/ana:/bin/bash
bo:x:1002:1002:Bo Chen:/home/bo:/bin/zsh
cy:x:1003:1003:Cy Patel:/home/cy:/bin/bash
dee:x:1004:1004:Dee Ross:/home/dee:/usr/sbin/nologin

scores.txt:

cy 72
ana 91
bo 85
dee 9
eve 100

fruit.txt:

apple
banana
apple
cherry
banana
apple
Apple

app.log is the six-line log from lesson 106.

cut: Extracting Parts of Lines

cut selects pieces of each line, either by field (-f) using a delimiter (-d), or by character position (-c).

Selecting Fields

cut -d: -f1 users.txt
ana
bo
cy
dee

-d: sets the delimiter to a colon, and -f1 selects the first field. Field numbers start at 1. Several fields and ranges can be listed:

cut -d: -f1,7 users.txt    # fields 1 and 7
cut -d: -f5- users.txt     # field 5 to the end
ana:/bin/bash
bo:/bin/zsh
cy:/bin/bash
dee:/usr/sbin/nologin
Ana Silva:/home/ana:/bin/bash
Bo Chen:/home/bo:/bin/zsh
Cy Patel:/home/cy:/bin/bash
Dee Ross:/home/dee:/usr/sbin/nologin

The selected fields are printed with the same delimiter between them. Ranges can also be written -3 (fields 1 to 3) or 2-4.

cut always prints fields in their original order. -f7,1 gives exactly the same output as -f1,7. To reorder columns, use awk (lesson 109).

GNU cut can change the delimiter in the output, or select everything except some fields:

cut -d: -f1,7 --output-delimiter=' -> ' users.txt
cut -d: --complement -f2,3,4 users.txt
ana -> /bin/bash
bo -> /bin/zsh
cy -> /bin/bash
dee -> /usr/sbin/nologin
ana:Ana Silva:/home/ana:/bin/bash
bo:Bo Chen:/home/bo:/bin/zsh
cy:Cy Patel:/home/cy:/bin/bash
dee:Dee Ross:/home/dee:/usr/sbin/nologin

--output-delimiter and --complement are GNU extensions; BSD cut on macOS does not have them.

Lines Without the Delimiter

A line that contains no delimiter at all is printed unchanged, which can let unexpected lines through. -s suppresses such lines:

printf 'a:b\nplain\nc:d\n' | cut -d: -f2
printf 'a:b\nplain\nc:d\n' | cut -s -d: -f2
b
plain
d
b
d

Selecting Characters

-c selects character positions, which suits fixed-width data such as the date and time at the start of each log line:

cut -c1-10 app.log | head -2
cut -c12-19 app.log | head -2
2026-11-20
2026-11-20
08:15:02
08:15:09

The Single-Delimiter Limitation

cut treats every delimiter character as a separator. Two spaces in a row therefore create an empty field between them. Consider spaced.txt, aligned with several spaces:

id   name    city
1    Ana     Lisbon
2    Bo      Oslo
cut -d' ' -f2 spaced.txt

The output is three empty lines: field 2 is the empty text between the first and second space. Two fixes are common. tr -s ' ' squeezes runs of spaces into one before cut:

tr -s ' ' < spaced.txt | cut -d' ' -f2
name
Ana
Bo

Or use awk, which treats any run of spaces and tabs as one separator by default:

awk '{ print $2 }' spaced.txt

That prints the same three lines. As a rule, cut is ideal for data with exactly one delimiter between fields, such as /etc/passwd, CSV without quoted fields, or tab-separated files (tab is cut's default delimiter).

sort: Ordering Lines

sort reads all its input, orders the lines and prints them. It must see the last line before it can print the first, so it cannot stream like grep.

Default Order and Numeric Order

By default sort compares whole lines as text:

sort scores.txt
ana 91
bo 85
cy 72
dee 9
eve 100

Sorting by a Field with -k

-k chooses which field to sort by. Fields are separated by blanks unless -t sets a delimiter. Sorting the scores as text by field 2 gives a surprising result:

sort -k2 scores.txt
eve 100
cy 72
bo 85
dee 9
ana 91

Text comparison works character by character, so 100 comes before 72 because 1 comes before 7. Adding n makes the comparison numeric:

sort -k2n scores.txt
dee 9
cy 72
bo 85
ana 91
eve 100

The form -k2,2 means "start at field 2 and end at field 2". Without the end, the key runs to the end of the line, which matters when there are more fields after the key. Options can be attached to the key; r reverses:

sort -k2,2nr scores.txt
eve 100
ana 91
bo 85
cy 72
dee 9

Delimiters and Multiple Keys

-t sets the field delimiter, and several -k options create primary, secondary and further keys. This sorts users by login shell, then by name:

sort -t: -k7,7 -k1,1 users.txt | cut -d: -f1,7
ana:/bin/bash
cy:/bin/bash
bo:/bin/zsh
dee:/usr/sbin/nologin

ana and cy share a shell, so the second key (field 1) decides their order.

When keys are equal, sort compares the whole line as a last resort. -s (stable) turns that off, so lines with equal keys keep their input order:

printf 'x 1 b\ny 1 a\n' | sort -k2
printf 'x 1 b\ny 1 a\n' | sort -s -k2,2
y 1 a
x 1 b
x 1 b
y 1 a

The first command's key runs to the end of the line (1 b versus 1 a), so a wins. In the second, the key is only field 2, both keys are 1, and -s keeps the original order.

Human-Readable Sizes

sizes.txt lists files with sizes such as those printed by du -h or ls -lh:

report.pdf 2.1M
notes.txt 12K
backup.tar 1.4G
photo.jpg 850K
data.csv 9K

-n reads only the leading number and ignores the suffix, giving a wrong order. GNU sort -h understands K, M and G:

sort -k2h sizes.txt
data.csv 9K
notes.txt 12K
photo.jpg 850K
report.pdf 2.1M
backup.tar 1.4G

Case, Locale and Duplicates

In the C locale, which was used for these examples, sort compares bytes, so all uppercase letters come before all lowercase letters:

LC_ALL=C sort fruit.txt
Apple
apple
apple
apple
banana
banana
cherry

In a language locale such as en_US.UTF-8, sort follows that language's collation rules instead, which usually place words differing only in case next to each other and can treat punctuation differently. Results then depend on the machine's settings. Scripts that need the same order everywhere set LC_ALL=C for the sort command, as above.

-f ignores case when comparing, and -u prints only the first of each group of equal lines:

sort -u fruit.txt
Apple
apple
banana
cherry

Apple and apple are different lines, so both remain. With -f -u they would count as equal.

Checking Whether Input Is Sorted

sort -c checks the order without printing the data. It reports the first line out of order and returns status 1:

sort -c scores.txt; echo "status $?"
sort scores.txt | sort -c; echo "status $?"
sort: scores.txt:2: disorder: ana 91
status 1
status 0

uniq: Collapsing Repeated Lines

uniq removes a line when it is identical to the line just before it. It only compares adjacent lines:

uniq fruit.txt
apple
banana
apple
cherry
banana
apple
Apple

Nothing was removed, because no two equal lines were next to each other. This is why uniq is almost always used after sort, which places equal lines together:

sort fruit.txt | uniq
Apple
apple
banana
cherry

For this simple case, sort -u does the same job in one command. uniq becomes necessary for its options.

Counting with -c

-c prefixes each line with the number of times it occurred:

sort fruit.txt | uniq -c
      1 Apple
      3 apple
      2 banana
      1 cherry

Adding a numeric reverse sort and head gives a frequency ranking, one of the most used pipelines in shell work:

sort fruit.txt | uniq -c | sort -rn | head -2
      3 apple
      2 banana

Other Options

sort fruit.txt | uniq -d     # only lines that appear more than once
sort fruit.txt | uniq -u     # only lines that appear exactly once
sort -f fruit.txt | uniq -ci # count, ignoring case
apple
banana
Apple
cherry
      4 Apple
      2 banana
      1 cherry

With -i, the group of four is shown with its first line, Apple. Note that sort -f was used so that the case variants are adjacent before uniq -i compares them.

-f N skips the first N fields when comparing:

printf '1 a\n2 a\n3 b\n' | uniq -f1
1 a
3 b

The first two lines differ only in field 1, so the second one was dropped.

wc: Counting Lines, Words and Characters

wc (word count) prints the number of lines, words and bytes of its input:

wc app.log
  6  42 333 app.log

app.log has 6 lines, 42 words (runs of non-space characters) and 333 bytes. Options select a single count:

OptionCounts
-lLines (newline characters)
-wWords
-cBytes
-mCharacters, according to the locale

With several files, wc adds a total:

wc -l app.log users.txt scores.txt
  6 app.log
  4 users.txt
  5 scores.txt
 15 total

Getting Just the Number

When a file name is given, wc prints it after the count. Reading from standard input instead gives only the number, which is what a script usually wants:

wc -l app.log
wc -l < app.log
n=$(wc -l < app.log)
echo "[$n]"
6 app.log
6
[6]

Lines Without a Final Newline

wc -l counts newline characters, not lines in the visual sense. A last line without a trailing newline is not counted:

printf 'one two\nthree' > nonl.txt
wc -l nonl.txt
wc -w nonl.txt
1 nonl.txt
3 nonl.txt

The file visibly has two lines, but only one newline. The word count still sees all three words. Files written by most editors and tools end with a newline, but files created by printf without \n or downloaded from some sources may not.

Bytes Versus Characters

-c counts bytes. -m counts characters, and in a UTF-8 locale a character such as é takes two bytes:

printf 'café\n' | wc -c
printf 'café\n' | LC_ALL=C.UTF-8 wc -m
6
5

In the C locale, wc -m also prints 6, because it treats each byte as a character there.

Combining the Tools

The real strength of these commands appears in pipelines. How many users use each login shell?

cut -d: -f7 users.txt | sort | uniq -c | sort -rn
      2 /bin/bash
      1 /usr/sbin/nologin
      1 /bin/zsh

Which log levels appear, and how often?

cut -d' ' -f3 app.log | sort | uniq -c | sort -rn
      3 INFO
      2 ERROR
      1 WARN

Each pipeline follows the same pattern: cut extracts the column of interest, sort groups equal values, uniq -c counts each group, and the final sort -rn puts the most frequent value first. For lines with equal counts, sort -rn falls back to comparing the whole line in reverse, which is why /usr/sbin/nologin comes before /bin/zsh.

To count matching lines, grep -c is shorter than grep ... | wc -l, and both give the same number:

grep -c ERROR app.log
2

The examples were run with GNU coreutils 9.4 in Bash 5.2.21.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Using cut, sort, uniq, and wc and get answers drawn from it.

Signed-in readers only.