Uses of the Linux Sort Command

Items to be sorted must be delimited in some way

Businessman using laptop in modern office
David Lees/Iconica/Getty Images

Data in a Linux text file can be sorted with the sort command as long as each element is delimited in some way. Frequently, the comma is used as the separator for delimited information.

Basic Rules for Sorting

The sort command rearranges the lines in a text file to sort them numerically and alphabetically. The default rules for the sort command are:

  • Text that starts with a number appears before text that starts with a letter; lower numbers sort first.
  • Text that starts with a letter that appears in the alphabet earlier that the first letter of other text entries is sorted before text that starts with a letter that appears later in the alphabet.
  • Where text begins with uppercase and lowercase instances of the same letter, the lowercase instance is sorted first.

Sorting a Text File

In order to sort the lines in a delimited Linux file, you use the sort command like this:

which sorts the file "test.txt" according to the characters starting at the second column (k2 refers to the second column). Assuming the input file content is:

Because the second column in this example contains first and last names, the sorted output is arranged by the first letter of the first name of each individual in the second column—Elvis, John, Johnny, Justin, Lady, Michael, Mick, and Taylor, as shown below:

If you sort the file with -k3 (using the line contents starting at column 3—the Title number column), the output is:

and

produces a list sorted by price:

Reversing a Sort

The -r option reverses the sorting. For example, using the results above:

yields:

Saving a Sorted File

Sorting a file doesn't save it. To save the sorted list in a file, you use the redirect operator:

where "test_new.txt" is the new file.

Sorting a Stream Output

You can also apply the sort command to the output of a stream, such as the pipe operator:

This sorts the output of the file listing generated by the ls command by file size, starting with largest files. The -n operator specifies numeric sorting rather than alphabetic.