Linux sort Command with Examples

March 24, 2022

Introduction

The sort command is a tool for sorting file contents and printing the result in standard output. Reordering a file's contents numerically or alphabetically and arranging information in ascending or descending order improves readability.

In this tutorial, you will learn to use the Linux sort command and see useful examples.

Linux sort command tutorial with examples.

Prerequisites

  • A system running Linux.
  • Access to a terminal.

Linux sort Syntax

The sort command has the following syntax:

sort [options] filename

Note: While the sort command arranges data in the specified order, the grep command displays or hides the specified information. Follow our tutorial to learn to use the grep command.

Running the sort command without [options] outputs the file's contents and applies the default sorting rules for the current locale.

The main rules are:

  • Lines starting with a number go before the lines beginning with a letter, arranged in ascending order (1-10).
  • Lines starting with letters are sorted in ascending alphabetical order (A-Z).

For example, the following file has multiple random lines:

Using the cat command to show a file's contents.

Run sort to arrange the file's contents in the default manner:

Sorting a file's contents using the sort command's default sorting rules.

The example above shows how the sort command arranges lines by default when no options are specified.

Note: The sort command assumes the data is in ASCII format. The locale settings affect the character's encoding and sorting. For example, to sort uppercase letters first, set the LC_ALL environment variable to the POSIX locale (C). Run LC_ALL=C to set the environment variable.

Linux sort Options

Specify an option to change the sort command sorting rules. The most used options are listed in the table below:

Short option formLong option formDescription
-b--ignore-leading-blanksCauses sort to ignore leading blanks.
-d--dictionary-orderCauses sort to consider only blanks and alphanumeric characters.
-f--ignore-caseIgnores the default case sorting rule and changes all lowercase letters to uppercase before comparison.
/--files0-from=FReads input from the files specified by NUL-terminated names in the specified F file. If F is -, sort reads names from standard input.
-M--month-sortSorts lines according to months (Jan-Dec).
-h--human-numeric-sortCompares human-readable numbers (e.g., 2K 1G).
-n--numeric-sortCompares data according to string numerical values.
-R--random-sortSorts data by a random hash of keys but groups identical keys together.
/--random-source=FILEGets random bytes from the specified FILE.
-r--reverseReverses the comparison results.
/--sort=WORDSort data according to the specified WORD: general-numeric -g, human-numeric -h, month -M, numeric -n, random -R, version -V.
-c--check, --check=diagnose-firstChecks if the input is already sorted but doesn't sort it.
/--debugAnnotates the part of the line used for sorting.
-k--key=KEYDEFSort data using the specified KEYDEF, which gives the key location and type.
-m--mergeCauses sort to merge already sorted files.
-o--output=FILERedirects the output to FILE instead of printing it in standard output.
-t--field-separator=SEPUses the specified SEP separator instead of non-blank to blank transition.
-z--zero-terminatedCauses sort to use NUL as the line delimiter instead of the newline character.
/--helpDisplays the help file with full options list and exits.
/--versionOutputs the program version and exits.

Linux sort Examples

Below are examples of using the sort command to arrange file contents in different ways.

Example 1: Save Output to File

The sort command only displays a file's contents after arranging them, but it doesn't change the file. However, the -o option allows you to save the sort command output to a file.

For example, the following command sorts the data in the default.txt file and saves the output to the sorted.txt file:

sort -o sorted.txt default.txt
Saving the sort command output in a file.

Running cat outputs the new file's contents.

Another way to save the sort command output is to redirect the output to a file:

sort default.txt > sorted.txt

Example 2: Check for Sorting in File

Specify the -c option to check if a file's contents have already been sorted. If the contents are already sorted, there's no output from the sort command.

However, when sort finds an unsorted line, it outputs a message reporting the first line is out of place.

For example:

sort -c default.txt
Checking if a file's contents are sorted using the sort command.

The command outputs a message reporting the number and contents of the first unsorted line.

Example 3: Sort Multiple Files

There are two ways to sort multiple files:

1. List filenames as arguments separated with a space.

Sort multiple files simultaneously by specifying the respective file names as arguments, separated by whitespace. The files' contents are joined together, sorted, and printed in standard output.

For example:

sort default1.txt default2.txt
Using sort to arrange the contents of multiple files simultaneously.

The command concatenates, sorts, and prints both files' contents.

2. Pipe the find command output to sort.

Another way to sort multiple files simultaneously is to pipe the find command output to sort and use the --files0-from= option in the sort command.

Specify the -print0 option in find to end file name with the NUL character and ensure the program properly reads the file list.

For example:

find -name "default?.txt" -print0 | sort --files0-from=-
Piping the find command output to sort to arrange the contents of multiple files simultaneously.

The example above concatenates and sorts the default1.txt and default2.txt files.

Example 4: Sort by Fields

By default, sort compares the entire line's contents and decides how to sort it. To compare according to a data subset, specify which fields to compare using the -k option.

The -k option takes the following syntax:

-k [ FStart [ .CStart ] ] [ Modifier ] [ , [ FEnd [ .Cend ] ][ Modifier ] ]
  • FStart. The beginning of the line.
  • CStart. The first column in the field.
  • Fend. The end of the line.
  • CEnd. The last column of the field.

The sort key includes all characters beginning with the field specified by the FStart variable and the column specified by the CStart variable. The key ends with the field specified by FEnd and the column specified by CEnd.

Not specifying Fend assumes the line's last character as the end. Without specifying CEnd, the last character in the FEnd field is assumed.

If there is any space between the fields, sort considers them as separate fields.

For example, the lines in the following file contain three fields:

Viewing a file's contents in the terminal with cat.

Sort the data based on the second field by running:

sort -k 2,2 school.txt
Sorting a file's contents with sort based on a specific field.

The command sorts the data according to the second field and ignores the first field.

Note: By default, sort assumes that fields are separated by whitespace. If there are multiple blank characters, sort considers them a part of the following field for sorting purposes. Specify the -b option to ignore any leading blank characters.

Example 5: Sort in Reverse Order

Use the -r option to sort the data in reverse order, i.e., in reverse alphabetical order or highest to lowest numbers.

For example, the following file is sorted with the default sorting rules:

sort default.txt
Sorting a file's contents with sort command default rules.

Specifying the -r option reverses the sorting order:

sort -r default.txt
Reverse sorting a file's contents.

Example 6: Remove Duplicate Entries

The -u option allows sort to remove duplicate entries from a file. For example, the following file has several duplicate entries:

Viewing a file with duplicate entries with cat.

Specifying the -u option sorts the data and removes the duplicate lines:

sort -u test.txt
Removing duplicate entries from a file output in sort.

Example 7: Sort by Months

Specify the -M option to arrange data according to months listed in a file.

To demonstrate sorting by months, create a file populated by the ls command output:

ls -l > month-sorting.txt
Redirecting the ls command output to a file.

Sort the data from the ls -l output by months by running the following command:

sort -Mk6 month-sorting.txt
Sorting a file's contents based on the months specified in the file.

The command sorts the file contents based on the sixth field containing the file creation month.

Example 8: Randomly Sort Data

Use the -R option to randomly arrange data without applying any sorting criteria.

For example, the following file contains several lines sorted numerically:

Viewing a file with ordered contents.

Mix up the line order with the following command:

sort -R ordered.txt
Randomly sorting a file's contents using the sort command.

The output shows that data is now randomly sorted.

Example 9: Specify a Delimiter

sort separates fields in a line using whitespace (spaces or tabs) as field delimiters. Specify the -t option to change the field delimiter to a different character.

For example, the following file contains multiple fields, including a person's name, job title, and place of residence:

Viewing a file with multiple fields.

Sorting the file by place of residence without changing the delimiter doesn't work because some cities have a space in the middle of their name. The space makes sort interpret the city name as two fields instead of one.

Change the delimiter to a comma (,) to properly sort the file's contents:

sort -t, -k4 school.txt
Changing the default delimiter in the sort command.

Changing the delimiter produces the desired output.

Example 10: Sort a Stream Output

Another way to supply input to the sort command is to use the pipe (|) operator. Piping into sort allows it to arrange another command's output and, optionally, save the results into a file.

The following example shows how to pipe the ls command output into sort and arrange the contents by file size:

ls -l /home/$USER | sort -nk5
Piping into the sort command and sorting the output based on file size.

The -nk5 options specify numeric sorting in the fifth field.

Conclusion

This tutorial showed how to use the sort command to rearrange a file's contents effectively. Easily arrange large data sets in an ascending or descending order using sort.

For more Linux commands and a downloadable PDF cheat sheet, refer to our Linux commands cheat sheet.

Was this article helpful?
YesNo
Bosko Marijan
Having worked as an educator and content writer, combined with his lifelong passion for all things high-tech, Bosko strives to simplify intricate concepts and make them user-friendly. That has led him to technical writing at PhoenixNAP, where he continues his mission of spreading knowledge.
Next you should read
How to Read Files Line by Line in Bash
March 17, 2022

This tutorial shows how to read a file line by line using the Bash shell. See five different methods and process a file's contents effectively...
Read more
How to Use the Linux history Command
May 30, 2024

the Linux bash shell saves a command history list, allowing you to review and reuse previous commands. Learn how to manage this list using...
Read more
How to Use the Linux at Command
February 2, 2022

The at command allows you to schedule a job for one-time execution. This guide shows how to install and use the at command, with several...
Read more
How to Use the dmesg Linux Command
January 18, 2022

The dmesg utility allows you to inspect the kernel ring buffer and check for errors during system startup. This tutorial shows how to use the...
Read more