HxHippy

sort

Sort lines of text files

Overview

Sorts the contents of a text file, line by line. Sorting is based on one or more sort keys extracted from each line.

Syntax

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

Common Options

-r, --reverse

Reverse the result of comparisons.

-n, --numeric-sort

Compare according to string numerical value.

-f, --ignore-case

Fold lower case to upper case for comparisons.

-u, --unique

With -c, check for strict ordering. Without -c, output only the first of an equal run.

-k POS1[,POS2], --key=POS1[,POS2]

Sort via a key; POS1 gives the start position and POS2 the end position (optional).

-t CHAR, --field-separator=CHAR

Use CHAR as field separator.

-o FILE, --output=FILE

Write result to FILE instead of standard output.

-C, --check=quiet, --check=silent

Check for sorted input; do not output anything, merely set exit status.

-m, --merge

Merge already sorted files; do not sort.

-h, --human-numeric-sort

Compare human readable numbers (e.g., 2K 1G).

Examples

$ sort names.txt

Sorts the lines in names.txt alphabetically.

$ sort -r data.txt

Sorts data.txt in reverse (descending) order.

$ ls -t | sort -k5 -n

Lists files and sorts them by size (5th field, numerically).

$ sort -u duplicates.txt

Sorts duplicates.txt and removes duplicate lines.

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

Sorts the /etc/passwd file numerically by the 3rd field (UID), using ':' as a delimiter.

$ sort data.txt -o sorted_data.txt

Sorts data.txt and saves the output to sorted_data.txt.

$ sort -C numbers.txt

Checks if numbers.txt is already sorted; prints nothing if sorted, an error otherwise.

$ sort -h sizes.txt

Sorts lines with human-readable sizes (like 1K, 2M) in sizes.txt.

sortorderalphabeticalnumericaluniquetextfile