/**/ How to use the sort command in Linux? - Dextutor - Linux

How to use the sort command in Linux?

We use the sort command in Linux to sort the content of a file. The sorted output is displayed on the screen.

Syntax of sort command

$sort [OPTION]… [FILE]…

Example

how to Use sort command in linux?
Use of sort command

Options used with sort command

-f: ignore case

                This option sorts the uppercase alphabets higher in order. The figure below shows the use of -f option where ‘Sort’ with capital ‘S’ appears first in the output.

Use of sort -f command
Use of sort -f

-n: numeric sort

                When you sort numbers, they are not sorted numerically by default which means by default first those numbers will be listed which start with 1, then with 2 and so on. But to sort numbers as we do in our daily routine we need to use -n option. See Figure below for example. Without the -n option the output is 115, 12, 15 … i.e., all numbers which start with 1 and then all numbers that start with 2 and so on. Whereas, with -n option the output is as expected. i.e., how we sort numbers in general

Use of sort -n
Use of sort -n

-M: month sort

                If you have data based on the month in your file and you want to get the analysis according to months then -M will help to sort the data month-wise. Figure 5 shows this in comparison to the normal sort.

Use of sort -M command
Use of sort -M

-r: reverse sort

                Use this option to sort the data in reverse order.

Use of sort -r command
Use of sort -r

-t: field separator

                By default, sort command will sort the data by comparing the first character and move to the next character when the first character is same and so on. But, in case the data is in the form of columns like a database file or a comma separated file and you want to sort the data according to a particular column then we specify the column using -k option and use -t option to specify the field separator. For example, in Figure 7, the field separator is ‘;’ and the data is sorted based on the second column

 use of sort -t command in linux
Use of sort -t

Practice Questions on How to use sort command in Linux?

Q1. Prepare a file as follows

Randell:13000:AP
Kim:2222:Cl
Thomas:1000:AP

The numerals represent salary of employees. Sort the above data based on salary

Q2. The /etc/passwd file contains the list of all users. Sort this file was per the usernames in reverse alphabetic order.

Q3. sort command sorts the content in descending order by default.

a) true
b) false

Relevant Commands