$linuxjunkies
>

sort(1)

Sort lines of text files in ascending or descending order based on specified keys and options.

UbuntuDebianFedoraArch

Synopsis

sort [OPTION]... [FILE]...

Description

The sort command arranges lines of text input in a specified order. By default it sorts alphabetically in ascending order, comparing entire lines. You can sort by specific fields, reverse the order, perform numeric sorting, and remove duplicates.

If no files are specified, sort reads from standard input. Multiple files are concatenated before sorting, or you can use the -m option to merge pre-sorted files.

Common options

FlagWhat it does
-nSort numerically instead of lexicographically; handles negative numbers and decimals correctly
-rSort in reverse (descending) order
-k POS1[,POS2]Sort by specific field(s); POS format is F[.C][OPTS] where F is field number, C is character position
-t SEPUse SEP as field delimiter instead of whitespace
-uRemove duplicate lines (keep only unique lines)
-fIgnore case differences; fold lowercase to uppercase
-o FILEWrite output to FILE instead of standard output
-mMerge already-sorted input files instead of sorting
-cCheck if input is sorted; return 0 if sorted, 1 otherwise
-VSort version numbers naturally (1.10 sorts after 1.9)
-iIgnore non-printable characters
--random-sortShuffle lines randomly instead of sorting

Examples

Sort lines in numbers.txt alphabetically and print to stdout

sort numbers.txt

Sort numerically; treats '9' as less than '10' (not '2' as in alphabetic sort)

sort -n numbers.txt

Sort in reverse (descending) order

sort -r numbers.txt

Sort /etc/passwd by UID (3rd field) numerically using colon as delimiter

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

Sort and remove duplicate lines, keeping only unique entries

sort -u data.txt

Sort primarily by 2nd field, then by 1st field (multi-key sort)

sort -k2,2 -k1,1 file.txt

Count occurrences of each line across multiple files and sort by frequency

cat file1.txt file2.txt | sort | uniq -c | sort -rn

Check if data.txt is sorted without printing output

sort -c -q data.txt && echo "File is sorted"

Related commands