VMware ESXi and vSphere Cluster Management

How to Sort Lines in a Text File with the Linux sort Command

Learn how to use Linux sort to order text lines alphabetically, reverse the order, sort by fields, check sortedness, and save results safely.

The Linux sort command orders text lines. It can read a named file or receive data through standard input, the default input stream for shell commands. Unless you redirect its output, the result goes to standard output, normally your terminal.

A line is treated as one record. By default, sort compares complete lines in ascending lexical order, meaning a text-based character comparison commonly described as alphabetical order.

Prepare example files

Create a file named words.txt with one word or phrase per line:

pear
apple
orange
banana

A second file can contain several whitespace-separated fields. Here, each line is a record with an identifier in field 1 and a name in field 2:

104 Zoe
101 Alice
103 Charlie
102 Bob

In this example, a field is a portion of a line separated from other portions by a delimiter. Blank space is the default field separator used by sort. A sort key is the field or character range used to decide how records are ordered.

Sort lines alphabetically

Pass the filename to sort:

sort words.txt

The command sends this result to standard output:

apple
banana
orange
pear

The source file remains in its original order. You can also sort data received from a pipe. A pipe sends the standard output of one command to the standard input of another:

printf '%s\n' pear apple orange | sort
apple
orange
pear

Reverse the selected order

Use -r to reverse the result:

sort -r words.txt
pear
orange
banana
apple

The -r option reverses the selected sort order. With no other options, it produces descending lexical order of complete lines.

Sort by a field or column

For multi-column records, use -k followed by a field number. Field numbering starts at 1, not 0. To sort the sample records by the second field, use:

sort -k2,2 sort1.txt

The form -k2,2 means that the key starts at field 2 and ends at field 2. Restricting both ends is useful because a key written only as -k2 can extend from field 2 through the rest of the line.

A sort1.txt record: 104 Zoe
Field 1: 104
Field 2: Zoe
Key:       ^^^

Expected output:

101 Alice
102 Bob
103 Charlie
104 Zoe
Input lineField 1Field 2Sort key used
104 Zoe104ZoeZoe from -k2,2
101 Alice101AliceAlice from -k2,2
103 Charlie103CharlieCharlie from -k2,2
102 Bob102BobBob from -k2,2

Because the second field is the key, the identifier in field 1 does not determine the primary order. If two records have equal key fields, other comparison rules can affect their relative order unless you provide additional options or keys.

Non-whitespace delimiters

Whitespace is the default separator. If a file uses another delimiter, such as a comma, specify it with -t. For example, a comma-separated file can be sorted by its second field with a command such as sort -t, -k2,2 data.csv. Confirm the file's delimiter before choosing a field key.

Core sort options

OptionPurposeExample
No optionAscending line sortingsort file.txt
-rReverse the resultsort -r file.txt
-k FIELD[,FIELD]Sort by a selected key or field rangesort -k2,2 file.txt
-cCheck whether input is already sortedsort -c file.txt

Check whether a file is sorted

Use -c to check ordering without printing a sorted version:

sort -c words.txt

If the file is correctly sorted, the command normally produces no output. If it finds disorder, it identifies the first line that is out of order and returns a nonzero exit status. An exit status is the numeric success or failure result returned by a command, which makes this option useful in scripts.

$ sort -c words.txt
sort: words.txt:3: disorder: apple

The exact diagnostic wording can vary between systems, but it indicates the first detected ordering problem. In a shell script, inspect the command's exit status rather than relying only on displayed text.

Save sorted output safely

Use shell redirection to write the result to a different file:

sort words.txt > words.sorted.txt

Redirection sends command output to a file. This command leaves words.txt unchanged and puts the sorted lines in words.sorted.txt.

When you need to replace the original, write the result to an intermediate file and move it into place after sort succeeds:

sort words.txt > words.tmp && mv words.tmp words.txt

The && operator runs mv only when sort completes successfully. For important data, keep a backup or use a carefully chosen temporary-file strategy.

Locale and character order

Sorting follows the system's locale and character-collation rules. As a result, uppercase and lowercase words may not appear in the order you expect, and results can differ between environments. When a reproducible byte-oriented order is required, choose a locale explicitly:

LC_ALL=C sort words.txt

Use the locale appropriate for your data and audience when human language collation matters.

Troubleshooting

  • The original file did not change: This is normal. Sort writes to standard output by default. Redirect to a separate file or use an intermediate file followed by mv.
  • Column sorting looks wrong: Check whether the file really uses whitespace as its separator. For a single-column key, prefer a precise range such as -k2,2. Use -t when the delimiter is not whitespace.
  • The file became empty: The input and redirected output filenames were probably the same. Never use sort file.txt > file.txt; write elsewhere first.
  • sort -c prints nothing: A silent result normally means the check succeeded. Check the exit status in scripts, or test an intentionally unsorted file to see its diagnostic.
  • Uppercase and lowercase order is surprising: Locale collation controls character ordering. Try an explicitly selected locale such as LC_ALL=C when consistent results are needed.

Quick reference

  1. Sort complete lines: sort words.txt
  2. Reverse the order: sort -r words.txt
  3. Sort by only the second whitespace-separated field: sort -k2,2 sort1.txt
  4. Check sortedness: sort -c words.txt
  5. Save without changing the source: sort words.txt > words.sorted.txt
  6. Replace safely through an intermediate file: sort words.txt > words.tmp && mv words.tmp words.txt

For a focused continuation of this lesson, see sorting lines of a text file.