Linux commands: sort

By

Published · Updated

Tagged: CLI

Learn how the Linux sort command orders the lines of a file or piped input, with -r to reverse, -n for numeric order, and -u to drop duplicate lines.

Suppose you have a text file which contains the names of dogs:

Terminal showing cat dogs.txt with an unsorted list of dog names: Roger, Syd, Vanille, Luna, Ivica, Tina

This list is unordered.

The sort command sorts them by name:

Terminal showing sort dogs.txt command with output alphabetically sorted: Ivica, Luna, Roger, Syd, Tina, Vanille

Use the -r option to reverse the order:

Terminal showing sort -r dogs.txt command with output in reverse alphabetical order: Vanille, Tina, Syd, Roger, Luna, Ivica

The order depends on your locale. With the C locale (LC_ALL=C sort) uppercase letters come before lowercase (byte order). In a UTF-8 locale like en_US.UTF-8, GNU sort uses a dictionary-like collation that mixes cases. Use -f (or --ignore-case) to ignore case.

Say scores.txt has:

10
2
1

Without -n, sort compares the text. 10 comes before 2, because 1 is before 2:

sort scores.txt
1
10
2
sort -n scores.txt
1
2
10

If the file contains duplicate lines:

The nano command on macOS (UW PICO 5.09) editing dogs.txt with duplicate entries: Roger, Syd, Vanille, Luna, Ivica, Tina, Roger, Syd

You can use the -u option to remove them. uniq does the same on already-sorted input:

Terminal showing sort -u dogs.txt command with duplicates removed: Ivica, Luna, Roger, Syd, Tina, Vanille

sort doesn’t just work on files. Like many UNIX commands it also works with pipes, so you can use it on the output of another command. For example you can order the files returned by ls with:

ls | sort

sort is very powerful and has lots more options, which you can explore calling man sort.

Terminal showing the first screen of man sort, with the NAME, SYNOPSIS and DESCRIPTION sections

The sort command works on Linux, macOS, WSL, and anywhere you have a UNIX environment

Line Sorter & Deduplicator

Sort, dedupe, filter, trim, and transform lines of text — operations compose, with live in/out stats.

Line sorter & deduplicatorInteractive · runs in your browser

Input

Operations (applied top to bottom)

Sort

Natural sort treats item2 before item10. Shuffle uses crypto.getRandomValues.

Output

lines in lines out duplicates removed

Want me to talk about your product? You can sponsor this site.

Related posts about cli: