How To

sort Command in Linux: Sort Text, Numbers, Columns, and More

The sort command in Linux reads lines from files or standard input and writes them to standard output in sorted order. By default, it sorts alphabetically in ascending order and never modifies the original file.

How to Use the sort Command in Linux

The syntax is:

bashsort [OPTIONS] [FILE]...

To sort a file alphabetically:

bashsort file.txt

sort writes the result to standard output. To save it, redirect the output:

bashsort file.txt > sorted.txt

Never redirect sort output back to the same file. The shell opens the output file for writing, truncating it to zero bytes, before sort even reads the input. sort file.txt > file.txt will empty your file. Use the -o option instead, which is safe for the same input and output file:

bashsort -o file.txt file.txt

To sort in reverse (descending) order:

bashsort -r file.txt

When multiple files are passed, their contents are merged and sorted together as a single stream, not sorted separately.

Sort Numerically, by Column, and Remove Duplicates

Alphabetical sort fails for numbers. The string 10 sorts before 2 because the character 1 comes before 2 in ASCII. sort compares characters one at a time, not values. Use -n to sort by numeric value:

bashsort -n numbers.txt

To sort numerically in reverse (largest first):

bashsort -nr numbers.txt

Sort by a specific column with -k. Fields are whitespace-separated by default. To sort by the second column numerically:

bashsort -k2 -n files.txt

To use a custom field delimiter, add -t. This example sorts /etc/passwd by the third field (UID) using : as the separator:

bashsort -t: -k3 -n /etc/passwd

Remove duplicate lines with -u. After sorting, any adjacent duplicate lines are dropped from the output:

bashsort -u file.txt

This produces the same result as sort file.txt | uniq, but -u is slightly more efficient because it removes duplicates during the sort pass. Piping to uniq separately is more flexible: uniq -c counts occurrences and uniq -d shows only the lines that appear more than once.

Check if Sorted, Human-Readable Sizes, and Pipelines

Check if a file is already sorted with -c. It exits silently if the file is in order, or prints an error and exits with a non-zero status if any line is out of place:

bashsort -c file.txt
sort: file.txt:2: disorder: banana

This is useful in scripts to validate input before processing it further.

Sort human-readable sizes with -h. Standard numeric sort (-n) only parses plain integers and cannot interpret SI suffixes like KM, or G. Use -h when working with output from du:

bashdu -sh /var/* | sort -h

-h correctly orders 4.0K16K1.2M, and 3.4G by magnitude rather than alphabetically.

Pipeline examples. sort is most powerful when combined with other tools:

Find the ten largest directories:

bashdu -sh /var/* | sort -rh | head -10

Count and rank the most frequent words in a file:

bashgrep -Eo '[[:alnum:]_]+' file.txt | sort | uniq -c | sort -rn

Sort a specific column from a CSV file:

bashcut -d',' -f2 data.csv | sort

The sort command handles most ordering tasks on its own, but it becomes a core building block for data processing when combined with uniqcuthead, and grep in pipelines. Leave a comment below if you run into any issues.

Cyber Defence

Recent Posts

wall Command in Linux: Broadcast Messages to Logged-In Users

The wall command in Linux sends a message to the terminals of all currently logged-in users. The…

14 minutes ago

journalctl Command in Linux: Query and Filter System Logs

journalctl queries logs collected by systemd-journald, the systemd logging daemon. It gives you structured access to kernel…

19 minutes ago

stat Command in Linux: View File and Filesystem Metadata

The stat command in Linux displays detailed metadata about files and filesystems. Where ls gives a condensed summary suitable…

24 minutes ago

groupadd Command in Linux: Create Groups and Set GID Options

In Linux, groups organize user accounts and define shared access to files and resources. Every…

1 day ago

touch Command in Linux: Create Files and Update Timestamps

The touch command in Linux does two things: it creates new empty files, and it updates the…

1 day ago

rsync Command in Linux: Sync Files, Mirror, and Transfer Remotely

The rsync command in Linux synchronizes files and directories between two locations, locally or over SSH. Unlike scp,…

2 days ago