Unix Sort Command with Syntax, Options and Examples

The Unix sort command is a simple command that can be used to rearrange the contents of text files line by line.

The command is a filter command that sorts the input text and prints the result to stdout. By default, sorting is done line by line, starting from the first character.

Numbers are sorted to be ahead of letters.

Lowercase letters are sorted to be ahead of uppercase letters.

Unix Sort Command with Examples

Sort Syntax:

sort [options] [files]

Sort Options:

Some of the options supported are:

sort -b: Ignore blanks at the start of the line.

sort -r: Reverse the sorting order.

sort -o: Specify the output file.

sort -n: Use the numerical value to sort.

sort -M: Sort as per the calendar month specified.

sort -u: Suppress lines that repeat an earlier key.

sort -k POS1, POS2: Specify a key to do the sorting. POS1 and POS2 are optional parameters and are used to indicate the starting field and the ending field indices. Without POS2, only the field specified by POS1 is used. Each POS is specified as “F.C” where F represents the field index, and C represents the character index from the start of the field.

sort -t SEP: Use the provided separator to identify the fields.

With the “-k” option, the sort command can be used to sort flat file databases. Without the “-k” option, the sorting is performed using the entire line. The default separator for fields is the space character. The -t option can be used to change the separator.

Examples:

Assume the below initial contents of file1.txt for the following examples

01 Priya 04 Shreya 03 Tuhina 02 Tushar

Sort with default ordering:

$ sort file1.txt
01 Priya
02 Tushar
03Tuhina
04 Shreya

In this example, the sorting is first performed using the first character. Since this is the same for all lines, the sorting then proceeds to the second character. Since the second character is unique for each line, the sorting ends there.

Sort in reverse ordering:

$ sort -r file1.txt
04 Shreya
03Tuhina
02 Tushar
01 Priya

In this example, the sorting is done similar to the above example, but the result is in the reverse order.

Sort by the second field:

$ sort -k 2 file1.txt
01 Priya
04Shreya
03Tuhina
02 Tushar

Now assume the original file2.txt is as below

01 Priya 01 Pooja 01 Priya 01 Pari

Sort with default ordering

$ sort file2.txt
01 Pari
01 Pooja
01Priya
01Priya

Sort suppressing repeated lines

$ sort -u file2.txt
01 Pari
01 Pooja
01Priya

Conclusion

The Sort command in Unix is a filter command that sorts the input text and prints the result to stdout. I hope the Unix sort command syntax and options explained in this post are helpful.