How to Use Sort Command in Unix

In this tutorial, we will show you how to use the sort command in unix. The sort command allows you to arrange the fields and data that are printed on the screen. This command assumes that the fields present are simply words that are just separated by means of blanks. However, an alternative parameter for selection of words can be specified e.g. colons. Output that is arranged from the sort command is printed on the screen unless it is redirected to a specific file.
To understand more about the sort commands follow the tutorial steps given below.

Step 1 – List the directory contents

First of all, let’s list the contents of the directory. Over here, you can see the file “alpha.txt” present.

View the contents of the directory

Step 2 – Read file in terminal application

To understand how sort command works, first let’s read the text file in the terminal application. For that, type the command “cat alpha.txt” and hit enter.
With that done, here you can see the contents of the text file on the screen.

View contents of the file

Step 3 – Sort the data being displayed on the screen

What if you wanted to sort the data being displayed on the screen.
For that, type the command “sort alpha.txt” and hit enter.
With that done, you can see that now the letters are being displayed in alphabetical order. Notice how the lowercases are printed first over here.

Sort the data to be displayed in output

Step 4 – Display the uppercase alphabets first

What if we wanted the uppercase alphabets to be printed first? For that, we will type in
“sort -f -s alpha.txt” and hit enter.
Now you can see that the uppercase are being displayed first. Over here, notice that we have multiple entries of the same alphabets

List the uppercase alphabets first

Step 5 – Display the unique entries

What if we want to display only the unique entries in the terminal application? For that, we will type this sort command in unix “sort -f – s -u alpha.txt” and hit enter.
With that done, you can see that now there are no duplicate entries over here

Enter command to view the unique entries

Step 6 – Sort the data in reverse

If want to sort the data in reverse, you can do that by typing:
“sort -f -r alpha.txt” and hitting enter.
With that done, you will notice that the letters over here are now being displayed in reverse.
And that’s basically how you can use the sort commands to arrange the data in different ways.

Enter command to sort data in reverse