Sort text files in place with Linux

The command sort is useful to order text lines. Sort orders alphabetically by default but there are options that enable you to order in other ways like in reverse alphabetical order or by string numerical value.

In this example I’ll demonstrate how to order a text file in place, that is, take a file and order all its lines alphabetically without making a copy first.

I got a file named namelist.txt which contains an unordered list of names.

John
Angela
Pedro
Victor
Omar

This file can be easily ordered in place with the following shell command.

sort -o namelist.txt namelist.txt

The result is the file with ordered text lines.

Angela
John
Omar
Pedro
Victor

Sort can help you keep text files ordered according to your requirements. I use it to order an alias dotfile after I add a new command at the bottom of the list. However, sort isn't useful for ordering source code, where arbitrary order is required.

Photo by Yan Ots on Unsplash

Jr. Software Developer and Computer Engineering graduate. Writes about technology and poetry. Creates glitch art. victoroalvarez.com/tree