Linux sort Command: Sort Text Lines

sort compares the lines of an input file and sends the sorted results to standard output. It is used not only for alphabetical sorting but also when numerical, specific field, or reverse sorting is needed.

The default sorting follows the character comparison rules of the current locale. The original file remains unchanged, and only the result is output, so to save the result, redirect to a separate file or use the GNU -o option. If a reproducible sort order is important, specify LC_ALL=C.

Basic syntax

sort [option] [file...]

The installed implementation and options may vary depending on the distribution. Check the description for your current system with man sort.

Examples

Basic sorting

Reads one line as a single record and sorts it. The output does not change the file.

sort names.txt

Sort by Number

When comparing numbers as characters, 10 can come before 2, so use -n.

sort -n scores.txt

Based on the Second Field

Compare the second field as a number in data separated by spaces. Suitable for input with a consistent field structure.

sort -k2,2n results.txt

View input and sort results together

The following example sorts three lines from standard input without creating a file. The default sort follows the character order of the current locale, and the original data remains unchanged.

printf 'zebra\napple\nbanana\n' | sort

Example output:

apple
banana
zebra

Lines containing numbers are compared as strings by default, so 10 may come before 2. If numerical comparison is intended, use sort -n. To sort a file and save it to a new file, specify the output path like sort source > result, and do not redirect to the same file directly. The shell may empty the input file first.

When sorting by multiple columns, specify each key's range explicitly. Use -s if rows with equal keys must keep their original relative order. Collation changes with the locale, so set an explicit environment such as LC_ALL=C when a script needs reproducible ordering.

Main Options and Format

Options/Format Description
-n Compare using numeric values.
-r Reverse the order of the results.
-k start,end Specify the key field to compare.
-u While sorting, leave only one result for duplicate comparison keys.
-t delimiter Specify the field separator character.

Precautions when using

sort -u can reduce lines with the same comparison key to one, so be careful if other fields in the original are important. To maintain the original order of the text while removing only adjacent duplicates, use uniq. Using > same_file on the input file may cause the shell to empty the file first.

Frequently Asked Questions

How do I save the sorted results to the original file?

In GNU sort, you can use sort -o names.txt names.txt. Make sure to back up important files first.

Official Documentation

You can check the exact behavior of the options and implementation-specific differences in the official documentation for sort.