The ‘sort’ command is a Linux program used for printing lines of input text files and concatenation of all files in sorted order. Sort command takes blank space as field separator and the entire input file as the sort key. It is important to notice that the sort command doesn’t actually sort the files but only prints the sorted output until you redirect the output.
This article aims at a deep insight into Linux ‘sort‘ command with 14 useful practical examples showing you how to use the sort command in Linux.
1. Creating a Text File with Specified Content
First, we will create a text file, named ‘tecmint.txt‘, which will be used for executing ‘sort‘ command examples in our working directory for this task is ‘/home/$USER/Desktop/tecmint‘.
The option ‘-e
‘ in the below command enables interpretation of backslash and /n
tells echo command to write each string to a new line.
echo -e "computer\nmouse\nLAPTOP\ndata\nRedHat\nlaptop\ndebian\nlaptop" > tecmint.txt
2. View File Contents
Before we begin with the ‘sort‘ command, let’s take a look at the contents of the file and how it appears using the following cat command.
cat tecmint.txt
3. Sorting File Content
The command “sort tecmint.txt” is used to rearrange the lines in the file in ascending alphabetical order, if there are any duplicate lines, it will keep one copy of each unique line.
sort tecmint.txt
4. Redirecting Sorted Output to New File
The following command is used to sort the lines of the text file “tecmint.txt” in alphabetical order and then redirects the sorted output to a new file named “sorted.txt“, which means that the original file remains unchanged, and the sorted content is stored in a separate file.
To verify the content, use the cat command.
sort tecmint.txt > sorted.txt cat sorted.txt
5. Sorting File Contents in Reverse Order
The following command is used to sort the lines of the text file “tecmint.txt” in reverse order, which means it will arrange the lines in descending alphabetical order and the sorted output is then redirected to a new file named “reversesorted.txt”
sort -r tecmint.txt > reversesorted.txt cat reversesorted.txt
6. Saving List of Files and Directories
The following command is used to list the contents of the user’s home directory (“/home/$USER“) in a detailed, long-format view using the ls command and then it redirects this directory listing to a text file named “lsl.txt” located on the user’s desktop, specifically in the “tecmint” directory.
ls -l /home/$USER > /home/$USER/Desktop/tecmint/lsl.txt cat lsl.txt
Now, we will explore examples of sorting the contents based on fields other than the default initial characters.
7. Sorting ‘File Contents Based on the Second Field
The following command is used to sort the contents of the file “lsl.txt” based on the values in the second field of each line. The '-n'
option indicates a numerical sort, treating the second field as numbers rather than text.
The '-k2'
option specifies that we want to sort based on the second field. By executing this command, you’ll obtain a sorted list of the lines in “lsl.txt“, with the sorting criteria being the numerical values in the second field of each line.
sort -nk2 lsl.txt
8. Sorting File Content Based on the Ninth Field
The following command is used to sort the lines in the file “lsl.txt” based on the values in the ninth field of each line in ascending order. The '-k9'
option specifies that the sorting should be done based on the ninth field.
sort -k9 lsl.txt
9. Sort Files by File Size
The following command combines the ‘ls‘ and ‘sort‘ commands to list the contents of the user’s home directory in a long listing format and then it pipes the directory listing to 'sort -nk5'
, which sorts the list based on the values in the fifth column, which represents file sizes.
ls -l /home/$USER | sort -nk5
10. Removing Duplicate Lines in File
The following command sorts the lines in the file “tecmint.txt” in ascending alphabetical order and removes any duplicate lines using the '-u'
option, which stands for “unique,” and it ensures that unique lines are retained in the sorted output.
$ cat tecmint.txt $ sort -u tecmint.txt
Rules so far (what we have observed):
- Lines starting with numbers are preferred in the list and lie at the top until otherwise specified (
-r
). - Lines starting with lowercase letters are preferred in the list and lie at the top until otherwise specified (
-r
). - Contents are listed based on the occurrence of alphabets in the dictionary until otherwise specified (
-r
). - Sort command by default treats each line as a string and then sorts it depending upon dictionary occurrence of alphabets (Numeric preferred; see rule – 1) until otherwise specified.
11. Redirecting Directory Listing to File
The following command lists the contents of the user’s home directory in long format, including hidden files and directories and then it redirects the directory listing to a text file named “lsla.txt” located on the user’s desktop within the “tecmint” directory.
ls -lA /home/$USER > /home/$USER/Desktop/tecmint/lsla.txt cat lsla.txt
Those familiar with the ls command understand that 'ls -lA'
is equivalent to 'ls -l'
plus hidden files. As a result, the majority of the contents in these two commands will be the same.
12. Sorting Contents of Files
The following command sorts the contents of two text files, ‘lsl.txt‘ and ‘lsla.txt‘, in ascending alphabetical order and then combines and displays the sorted content in the terminal.
$ sort lsl.txt lsla.txt
Notice the repetition of files and folders.
13. Removing Duplicate Lines in File
The following command merges and sorts the contents of two text files, ‘lsl.txt‘ and ‘lsla.txt‘, in ascending alphabetical order while removing any duplicate lines using the '-u'
option, which ensures that unique lines are retained in the sorted output.
$ sort -u lsl.txt lsla.txt
Notice that duplicates have been omitted from the output. Additionally, you can save the output to a new file by redirecting it.
14. Sorting Output by Multiple Fields Using Custom Delimiter
The following command combines the ‘ls‘ and ‘sort‘ commands to list the contents of the user’s home directory in long format and then it pipes the directory listing to the ‘sort‘ command, which sorts the output based on specific columns and fields.
ls -l /home/$USER | sort -t "," -nk2,5 -k9
Here’s a breakdown of the command:
-t ","
– specifies that a comma(",")
is used as the field delimiter.-nk2,5
– indicates sorting by a numerical value in columns 2 to 5, which typically represent permissions and ownership details.-k9
– further sorts the result based on the ninth column, which represents file sizes.
That’s all for now. In the next article, we will delve into more detailed examples of the sort command for you.
Please continue to share, comment, like, and help us reach a wider audience.
In “7. Sort the contents of file ‘lsl.txt‘ on the basis of 2nd column (which represents number of symbolic links).”
It is incorrect to say “symbolic links“. It’s the number of links, “hard” if you want to distinguish.
@Cschanzie,
Thank you for the correction, I have updated the article regarding “number of links” being “hard” is much appreciated.
We’ll ensure the accurate terminology is used in the article.
1. A key specification like
-k2
means to take all the fields from 2 to the end of the line into account. To sort by a single column, use-k2,2
as the key specification. This means to use the fields from #2 to #2, i.e. only the second field.2. While doing something like “
sort -nk5,5 table.txt
“, why does the sort command remove entries with 0? (have files with size 0-should get sorted not removed)The link to 7 Interesting Sort Commands does not work properly. It loads this article
There are only 10 ‘sort’ command examples. The other four entries just create files to be input to the ‘sort’ command examples.
Hi!
Just wondering why you type ”/home/$USER/” instead of just ”$HOME/”. Unnecessary typing. Just saying. :) Or am I missing something?
In the last command:
$ ls -l /home/$USER | sort -t "," -nk2,5 -k9
Why you put a parameter -t ? I don’t understand…
I have a copy of a 4.09 GB wordlist / dictionary, crackstation.txt. Just now the words and numbers are arranged in the usual order: 0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStT uUvVwWxXyYzZ
How do I rearrange the order to something like:
tTaAsShHwWiIoObBmMfFcCdDpPnNeEgGrRyYuUvVjJkKqQzZxX 1023985467
(This sequence gives the first letters of English words in order of popularity, from most popular (left) to least popular (right))
“14 Useful Examples…”
No, it’s 14 numbered entries, but several are just duplicate functions of sort using files vs using standard input.
Hello, what program are you use to create gif such as above?