← All commands
THE COMMAND REFERENCE

sort

Sort lines of text.

Last updated

BusyBox

Implementation-level reference; examples are not certified for every installed version.

Overview

sort reads lines from files or standard input and prints them in order. By default it compares text using the current locale, so punctuation, case, and numbers sort as text.

Background

A sort command first appeared in Version 1 Unix, according to the FreeBSD and macOS manuals. Today the name covers GNU sort, the sort that macOS ships, and the sort applet in BusyBox. They agree on -r, -n, -u, -t, and -k, and differ on options such as -h and -V.

Examples

Sort lines alphabetically:

sort fruit.txt

Sort in reverse order:

sort -r fruit.txt

Sort numbers by value instead of as text:

sort -n nums.txt

Sort and drop duplicate lines:

sort -u fruit.txt

Sort a comma-separated file by its second column; the header sorts first because it has no number:

sort -t, -k2,2n data.csv

Find the largest number:

sort -rn nums.txt | head -n 1

Options

-r
Reverse the order.

-n
Compare as numbers, not text. Without it, 10 sorts before 9.

-u
Output only the first of lines that compare equal, which also removes duplicates.

-t
Set the field separator for -k to this single character, as in -t,.

-k
Sort by a field or character range. -k2,2n means start and stop at field 2, numerically; without the
,2 the key runs to the end of the line.

Common mistakes

Without -n, numbers sort as text, so 10 comes before 9. Order depends on the locale: the examples here use the C locale (LC_ALL=C) for predictable results, and other locales can sort case and punctuation differently. sort file > file empties the file before sorting; write to another file.

Portability

-r, -n, -u, -t, and -k are in the Common examples. The Common examples were executed on GNU coreutils 9.11, macOS system tools, and BusyBox 1.37.0 (see the development guide for the exact check). Version sort -V, human-numeric -h, and stability options differ between builds.

About BusyBox sort

BusyBox bundles sort as an applet, and anything beyond the common options depends on how it was built. This page's examples ran on BusyBox 1.37.0.

BusyBox notes

BusyBox sort supports the common options above. Options such as -h, -V, and --parallel depend on the build configuration.

References

Original explanations, with upstream documentation for further reading. FreeBSD references are comparison material, not a claim of Apple version equivalence.