Hello again. Today we will teach you another very useful command in the manipulation of text files, such as the sort command.
What does the sort command do?
The sort command sorts lines of input files based on sorting criteria. This command is quite useful for many sysadmins who handle text files daily. In addition to this, the sort command is very flexible and sorts efficiently according to your needs.
One of the advantages of sort is that since it is part of the GNU Core Utils we can use it natively in the system. That is to say, that we do not have to install or to configure something extra.
Like many other commands, the sort command has options that modify its behavior. In this post, we will help you to use them according to the circumstances.
Let’s go for it.
Using the sort command in Linux
The basic syntax of the
sort command is as follows
sort [option] [file]
So if we start from a file named
example.txt whose contents are as follows
Motor Scar Car Op
And we use the
sort command without options
You will get an output screen like the following one
Car Motor Op Scar
To reverse the order, you have to use the
-r option, so you will get a different result.
sort -r example.txt
As I always say, upper and lower case can be a problem in text files. To make the sort ignore them, just use the
sort -f example.txt
Another useful option is the
-u option, which allows us to check if the file is already sorted.
sort -u example.txt
If you do not get any output on the screen, it is already sorted.
If you want to sort and at the same time remove duplicates, you can use the
sort -u example.txt
-k option and a number, you can specify which field is to be referenced.
For example, let’s start from a file named
example2.txt that has the following content
1010 Aaron Trunk 1598 Zac Eron 3578 Fabian mo
We can set it to be sorted by name. That is to say, by the second field of the text line.
sort -k 2 example2.txt
1010 Aaron Trunk 3578 Fabian mo 1598 Zac Eron
As you can see, it is basic to use the
sort command. If you are going to sort numbers, then use the
sort -n file.txt
You can combine it with the
sort -nr file.txt
Or if you have a file with months, the right option is
sort -M file.txt
So enjoy it.
In this post, you have learned how to use the sort command to sort text files. Quite useful in configurations and especially for manipulating this kind of files via the terminal.