sort Command Examples

Powerful Text Sorting and Ordering Utility

About sort

The sort command is a fundamental Unix/Linux utility that sorts lines of text files or standard input. It's one of the most frequently used commands in shell scripts and data processing pipelines. Sort provides extensive options for customizing the sorting behavior, including numeric sorting, reverse ordering, field-based sorting, and handling of unique values.

Key Features:

💡 Note: The sort command is part of GNU coreutils and is available on all Linux/Unix systems by default. It can handle very large files efficiently using external merge-sort algorithms.

Command Syntax

sort [OPTIONS] [FILE(s)]

Essential Options

Option Description Example
-r Reverse order (descending) sort -r file.txt
-n Numeric sort sort -n numbers.txt
-h Human-readable numbers (K, M, G) sort -h sizes.txt
-k Sort by specific field/column sort -k2 data.csv
-t Field delimiter sort -t: -k3 /etc/passwd
-u Unique (remove duplicates) sort -u file.txt
-f Ignore case sort -f names.txt
-o Output to file sort -o output.txt input.txt
-c Check if sorted sort -c file.txt
-m Merge sorted files sort -m file1.txt file2.txt

Detailed Examples

Example 1: Basic Alphabetic Sorting

cat << EOF | sort
zebra
apple
banana
cherry
apricot
EOF
apple
apricot
banana
cherry
zebra
Basic sort arranges lines in alphabetical (lexicographic) order:
  • Default behavior: ascending alphabetical order
  • Case-sensitive by default (uppercase comes before lowercase)
  • Sorts entire lines, not individual words
  • Based on ASCII values when comparing characters
This is the most fundamental use case and the default sorting method.
💡 Pro Tip: To sort in descending order, add the -r flag: sort -r file.txt

Example 2: Numeric Sorting

cat << EOF | sort -n
100
20
3
1500
45
EOF
3
20
45
100
1500
The -n option enables numeric sorting, treating strings as numbers:
  • Without -n: lexicographic sort would give 100, 1500, 20, 3, 45
  • With -n: numbers are compared by value, not string
  • Handles negative numbers correctly
  • Ignores leading whitespace and non-numeric characters
Essential for sorting file sizes, port numbers, PIDs, or any numeric data.

🔍 Comparison:

# Without -n (lexicographic)
echo -e "100\\n20\\n3" | sort
# Output: 100, 20, 3

# With -n (numeric)
echo -e "100\\n20\\n3" | sort -n
# Output: 3, 20, 100

Example 3: Human-Readable Numeric Sorting

cat << EOF | sort -h
1K
500M
2G
100K
50M
1.5G
EOF
1K
100K
50M
500M
1.5G
2G
The -h option sorts human-readable sizes (K, M, G, T, P, E, Z, Y):
  • Recognizes SI suffixes: K (1000), M (1000²), G (1000³), etc.
  • Perfect for sorting output from du -h, df -h, ls -lh
  • Handles decimal values correctly (1.5G, 2.3M)
  • Case-insensitive for suffixes
Invaluable for system administration tasks involving file sizes and disk usage.

📊 Real-world usage:

# Sort directories by size
du -sh * | sort -h

# Find largest files
ls -lh | sort -k5 -h | tail -5

Example 4: Sort by Specific Field/Column

cat << EOF | sort -k2
John 25
Alice 30
Bob 20
Charlie 35
EOF
Bob 20
John 25
Alice 30
Charlie 35
The -k option specifies which field (column) to sort by:
  • -k2 - Sort by second field (space-delimited by default)
  • -k2n - Sort second field numerically
  • -k2,2 - Sort by second field only (don't use subsequent fields as tiebreakers)
  • -k2nr - Sort second field numerically in reverse
Field numbering starts at 1, not 0.
💡 Advanced: You can specify multiple sort keys: sort -k2n -k1 sorts by second field numerically, then by first field alphabetically for ties.

Example 5: Custom Field Delimiter

cat << EOF | sort -t: -k3n
root:x:0:0:root:/root:/bin/bash
craig:x:1000:1000:Craig:/home/craig:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
EOF
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
craig:x:1000:1000:Craig:/home/craig:/bin/bash
The -t option specifies a custom field delimiter:
  • -t: - Use colon as delimiter (common in /etc/passwd)
  • -t, - Use comma as delimiter (CSV files)
  • -t$'\\t' - Use tab as delimiter (TSV files)
  • Combined with -k to sort by specific fields
This example sorts /etc/passwd entries by UID (3rd field) numerically.

📁 CSV Example:

# Sort CSV by 3rd column (price)
sort -t, -k3n products.csv

# Sort by 2nd column alphabetically, then 3rd numerically
sort -t, -k2 -k3n products.csv

Example 6: Remove Duplicates with Unique Sort

cat << EOF | sort -u
apple
banana
apple
cherry
banana
apple
EOF
apple
banana
cherry
The -u option removes duplicate lines while sorting:
  • Combines sorting and deduplication in one pass
  • More efficient than sort | uniq
  • Keeps only the first occurrence of each unique line
  • Can be combined with other options: sort -un, sort -ur
Perfect for cleaning up lists, log files, or data with redundant entries.
⚡ Performance: sort -u is faster and more memory-efficient than sort | uniq because it eliminates duplicates during the sort operation.

Example 7: Case-Insensitive Sorting

cat << EOF | sort -f
Zebra
apple
Banana
CHERRY
Apricot
EOF
apple
Apricot
Banana
CHERRY
Zebra
The -f (fold case) option makes sorting case-insensitive:
  • Treats uppercase and lowercase as equivalent
  • Without -f: uppercase letters sort before lowercase
  • Useful for sorting names, file lists, or mixed-case data
  • Can be combined with other options: sort -fu
Essential when case variations shouldn't affect sort order.

🔄 Comparison:

# Case-sensitive (default)
echo -e "Zebra\\napple\\nBanana" | sort
# Output: Banana, Zebra, apple

# Case-insensitive
echo -e "Zebra\\napple\\nBanana" | sort -f
# Output: apple, Banana, Zebra

Example 8: Reverse (Descending) Sort

cat << EOF | sort -rn
45
12
89
3
67
EOF
89
67
45
12
3
The -r option reverses the sort order (descending):
  • sort -r - Reverse alphabetic sort
  • sort -rn - Reverse numeric sort (largest first)
  • sort -rh - Reverse human-readable sort
  • Can be applied to specific fields: sort -k2rn
Commonly used to find largest values, most recent dates, or top items.

📈 Common Use Cases:

# Find largest files
du -sh * | sort -rh | head -10

# Show processes using most CPU
ps aux | sort -k3rn | head -10

# Latest log entries first
sort -r access.log

Example 9: Check If File Is Sorted

# Create test files
echo -e "1\\n2\\n3" > sorted.txt
echo -e "3\\n1\\n2" > unsorted.txt

# Check if sorted
sort -c sorted.txt && echo "File is sorted" || echo "File is not sorted"
sort -c unsorted.txt && echo "File is sorted" || echo "File is not sorted"
File is sorted
sort: unsorted.txt:2: disorder: 1
File is not sorted
The -c (check) option verifies if a file is already sorted:
  • Returns exit code 0 if sorted, non-zero if not
  • Reports first out-of-order line
  • Doesn't produce output unless there's an error
  • Useful in scripts to avoid unnecessary sorting
  • -C variant is silent (no error messages)
Helps optimize scripts by checking sort status before processing.
🔧 Script Usage: Use sort -c file.txt 2>/dev/null in scripts to silently check sort status via exit code.

Example 10: Advanced Multi-Key Sorting with Real Data

cat << EOF > employees.csv
Name,Department,Salary,Years
Alice,Engineering,95000,5
Bob,Sales,75000,3
Charlie,Engineering,105000,8
Diana,Sales,80000,4
Eve,Engineering,90000,4
Frank,Marketing,70000,2
Grace,Engineering,110000,10
EOF

# Sort by department, then by salary (descending)
tail -n +2 employees.csv | sort -t, -k2 -k3rn
Grace,Engineering,110000,10
Charlie,Engineering,105000,8
Alice,Engineering,95000,5
Eve,Engineering,90000,4
Frank,Marketing,70000,2
Diana,Sales,80000,4
Bob,Sales,75000,3
Complex real-world example demonstrating multiple sort keys:
  • tail -n +2 - Skip header line
  • -t, - Use comma as field delimiter
  • -k2 - Primary sort by department (alphabetically)
  • -k3rn - Secondary sort by salary (numeric, descending)
This groups employees by department and lists highest-paid first within each department.

🎯 More Complex Scenarios:

# Sort by dept (ascending), years (descending), then salary (descending)
tail -n +2 employees.csv | sort -t, -k2 -k4rn -k3rn

# Sort and save with header
(head -n1 employees.csv && tail -n +2 employees.csv | sort -t, -k2 -k3rn) > sorted_employees.csv

# Sort by multiple fields with different delimiters
sort -t: -k3n -k4n /etc/passwd

Special Sort Techniques

Random Shuffle

# Randomly shuffle lines
sort -R file.txt

# Create random sample
sort -R large_file.txt | head -100 > sample.txt
The -R option randomly shuffles lines instead of sorting them. Useful for randomizing data, creating test samples, or shuffling playlists.

Version Number Sorting

cat << EOF | sort -V
file-1.10.txt
file-1.2.txt
file-1.20.txt
file-1.3.txt
EOF
file-1.2.txt
file-1.3.txt
file-1.10.txt
file-1.20.txt
The -V option sorts version numbers correctly, treating numeric components intelligently. Essential for sorting software versions, file backups, or numbered files.

Month Name Sorting

cat << EOF | sort -M
Dec
Jan
Mar
Feb
EOF
Jan
Feb
Mar
Dec
The -M option sorts month names (Jan, Feb, etc.) in calendar order. Works with full or abbreviated month names.

Real-World Use Cases

Use Case 1: System Administration

# Find users with highest UIDs
sort -t: -k3rn /etc/passwd | head -10

# List processes by memory usage
ps aux | sort -k4rn | head -20

# Find largest directories
du -sh /* 2>/dev/null | sort -rh

# Sort log files by timestamp
sort -t' ' -k1M -k2n access.log

Use Case 2: Data Analysis

# Count and sort unique IPs in log
awk '{print $1}' access.log | sort | uniq -c | sort -rn

# Sort CSV by multiple columns
sort -t, -k3rn -k2 sales_data.csv

# Find most frequent error codes
grep ERROR app.log | awk '{print $5}' | sort | uniq -c | sort -rn

# Merge sorted files
sort -m sorted1.txt sorted2.txt sorted3.txt > combined.txt

Use Case 3: Text Processing

# Create sorted unique word list from text
tr ' ' '\\n' <document.txt | sort -fu > words.txt

# Sort and remove blank lines
sort file.txt | sed '/^$/d'

# Sort lines by length
awk '{print length, $0}' file.txt | sort -n | cut -d' ' -f2-

# Alphabetize configuration file sections
sort -t= -k1 config.ini

Performance Considerations

⚡ Performance Tips:

Optimized Large File Sorting

# Sort very large file efficiently
TMPDIR=/fast/storage sort -S 2G --parallel=8 --compress-program=gzip huge_file.txt -o sorted_output.txt

# Check progress (use pv if available)
pv huge_file.txt | sort -S 2G > sorted_output.txt

Stability in Sorting

🎯 Sort Stability: The sort command is stable by default, meaning it preserves the relative order of records with equal keys. This is crucial when performing multi-pass sorts:
# Two-pass stable sort
sort -k2 file.txt | sort -s -k1

# The -s flag explicitly requests stable sort

Common Pitfalls and Solutions

Pitfall 1: Locale Affects Sorting

⚠️ Issue: Different locales can produce different sort orders.
# Problem: Unexpected sort order
sort file.txt # Uses current locale

# Solution: Use consistent locale
LC_ALL=C sort file.txt # ASCII byte order
LANG=en_US.UTF-8 sort file.txt # Specific locale

Pitfall 2: Numeric vs. Lexicographic

⚠️ Issue: Forgetting -n for numeric data.
# Wrong: lexicographic sort on numbers
sort numbers.txt # Gives: 1, 10, 100, 2, 20, 200

# Correct: numeric sort
sort -n numbers.txt # Gives: 1, 2, 10, 20, 100, 200

Pitfall 3: In-Place Sorting

⚠️ Issue: Cannot redirect output to input file directly.
# WRONG - Destroys file!
sort file.txt > file.txt # File becomes empty!

# CORRECT - Use -o option
sort file.txt -o file.txt # Safe in-place sort

# Alternative - Use temporary file
sort file.txt > temp && mv temp file.txt

Integration with Other Commands

Powerful Pipeline Examples

# Top 10 most common words in text
tr -cs A-Za-z '\\n' < document.txt | tr A-Z a-z | sort | uniq -c | sort -rn | head -10

# Find duplicate files by size
find . -type f -exec ls -l {} \\; | awk '{print $5, $9}' | sort -n | uniq -d -w 10

# Sort and format output
ps aux | tail -n +2 | sort -k3rn | awk '{printf "%-10s %5s%% %s\\n", $1, $3, $11}' | head -10

# Merge and deduplicate multiple sorted files
sort -mu file1.txt file2.txt file3.txt -o combined_unique.txt

Related Commands

Quick Reference

Most Common Sort Commands

# Basic sort
sort file.txt

# Numeric sort
sort -n numbers.txt

# Reverse sort
sort -r file.txt

# Unique sorted output
sort -u file.txt

# Sort by 2nd field
sort -k2 data.txt

# Sort CSV by 3rd column numerically
sort -t, -k3n data.csv

# Human-readable size sort
du -sh * | sort -h

# Case-insensitive unique sort
sort -fu names.txt

# Sort and save in-place
sort file.txt -o file.txt