← All commands
THE COMMAND REFERENCE

sort

Sort lines of text.

Last updated

GNU

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 GNU sort

GNU sort is part of GNU coreutils, and this page's checks ran coreutils 9.11. It adds options such as -h for human-readable sizes and -V for version order.

GNU notes

GNU sort adds options such as -h (human-readable sizes like 2K or 1G) and -V (version order). Confirm that a macOS or BusyBox build provides an option before depending on it.

References

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