How to alphabetically sort a text file in Linux

In this article, we cover how to alphabetically sort a text file in Linux. If we have got a list in a text file that needs to be arranged alphabetically then we can use the sort command-line utility. It can get the list sorted both ways i.e. in ascending as well as descending order.

Let’s understand it with the help of an example. We have a list, new.txt which has the following contents in it.

ABC 1000
XYZ 400
DEF 22000
FGH 5500
YRT 79

We can use the nano text editor to save the above data in the file new.txt.

Alphabetically sort a text file in Linux

Now, use the sort command-line utility:

sort new.txt

It would get us the sorted data in the standard output:

ABC 1000
DEF 22000
FGH 5500
XYZ 400
YRT 79

And, if you use the cat command-line utility to read the contents of the new.txt file:

cat new.txt

It still shows the unsorted data:

ABC 1000
XYZ 400
DEF 22000
FGH 5500
YRT 79

At this stage, we have got two options with us. Either we save the sorted contents to a different file or save them in the source file itself.

We first start with saving the output in a different file. It can be done through the following command:

sort new.txt >> sorted-new.txt

On the other hand, if we want then save it to the source file itself. It is important to understand that this would make permanent changes to our source file.

sorted -o new.txt new.txt

What we have covered till now is about, sorting the data in ascending order. In case we wish to do the reverse sort i.e. in descending order then use the -r option. So, the above two commands, in that case, would be:

sort -r new.txt >> sorted-new.txt

and,

sorted -ro new.txt new.txt

In conclusion, we have covered how to sort a text file alphabetically in Linux here.

Additional Info:

If we want to sort on the basis of data in the second column containing numerical values, then

sort sort -n -k 2 new.txt

where -n is for numeric sort and -k is for sorting it through a key. We cover numeric sorting in the coming articles.

Similar Posts