14 Useful Examples of ‘Sort’ Command in Linux – Part 1

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

Split String by Lines in Linux

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

Check Content of File

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

Sort Content of File linux

Note: The above command doesn’t sort the contents of the text file but only displays the sorted output on the terminal.

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

Sort File Content in Linux

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

Sort Content By Reverse

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

Populate Output of Home Directory

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

Sort Content by Column

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

Sort Content Based on Column

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

Sort Content Using Pipe Option

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

Sort and Remove Duplicates

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

Populate Output With Hidden Files

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

Sort Contents of Two Files

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

 Sort, Merge and Remove Duplicates from File

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.

Sort Content By Field Column

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.

Hey TecMint readers,

Exciting news! Every month, our top blog commenters will have the chance to win fantastic rewards, like free Linux eBooks such as RHCE, RHCSA, LFCS, Learn Linux, and Awk, each worth $20!

Learn more about the contest and stand a chance to win by sharing your thoughts below!

Ravi Saive
I am an experienced GNU/Linux expert and a full-stack software developer with over a decade in the field of Linux and Open Source technologies

Each tutorial at TecMint is created by a team of experienced Linux system administrators so that it meets our high-quality standards.

Join the TecMint Weekly Newsletter (More Than 156,129 Linux Enthusiasts Have Subscribed)
Was this article helpful? Please add a comment or buy me a coffee to show your appreciation.

9 Comments

Leave a Reply
  1. 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.

    Reply
    • @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.

      Reply
  2. 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)

    Reply
  3. 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.

    Reply
  4. Hi!
    Just wondering why you type ”/home/$USER/” instead of just ”$HOME/”. Unnecessary typing. Just saying. :) Or am I missing something?

    Reply
  5. 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))

    Reply
  6. “14 Useful Examples…”

    No, it’s 14 numbered entries, but several are just duplicate functions of sort using files vs using standard input.

    Reply

Got Something to Say? Join the Discussion...

Thank you for taking the time to share your thoughts with us. We appreciate your decision to leave a comment and value your contribution to the discussion. It's important to note that we moderate all comments in accordance with our comment policy to ensure a respectful and constructive conversation.

Rest assured that your email address will remain private and will not be published or shared with anyone. We prioritize the privacy and security of our users.