Sort lines of a text file

The sort command is used to sort the lines of a text file in Linux. You can provide several command line options for sorting data in a text file.

Here is an example file:

linux sort example file

To sort the file in alphabetical order, we can use the sort command without any options:

linux sort command

To sort in reverse, we can use the -r option:

linux sort in reverse

We can also sort on the column. For example, we will create a file with the following text:

linux sort example 2

Blank space is the default field separator. This means that we can sort the text pictured above by the second column. To do that, the -k option, along with the field number, is used:

linux sort by column

In the picture above, we have sorted the file sort1.txt in alphabetical order using the second column.

To check if a file is already sorted, use sort with the -c option. This option also reports the first unsorted line:

linux sort check

Subscribe to our Newsletter

Like us on Facebook

Geek University 2019