Command sort is used to display/arrange the content of the text file in ascending or descending order.
By default, sort command sorts the entire lines.
Syntax:
1 | $ sort filename [press enter] |
Example:
Suppose we have a file Employee.txt as shown below and we want to sort the content of the file and display at the terminal. By default sort command sorts the entire lines.
File 1: Employee.txt
1 | $ sort Employee.txt [press enter] |
Output
1 2 3 4 | Aditya | DGM | 100000 | 03-02-1987 | 30 | Kumar | GM | 700000 | 05-02-1977 | 41 | Manish | CA | 500000 | 10-02-1997 | 20 | Rajeev | CLERK | 300000 | 05-05-1987 | 31 | |
Options of sort command
Primary key (-k): Option (–k) is used to sort specific field. Suppose we want to perform shorting according to second field then the command is as follows:
1 | $ sort -t “|” -k 2 Employee.txt [press enter] |
Output:
1 2 3 4 | Manish | CA | 500000 | 10-02-1997 | 20 | Rajeev | CLERK | 300000 | 05-05-1987 | 31 | Aditya | DGM | 100000 | 03-02-1987 | 30 | Kumar | GM | 700000 | 05-02-1977 | 41 | |
NOTE: Option –t is used to specify delimiter. Here in the above file Employee.txt, we have used “|” as a delimiter. We can also other delimiters.
1 | Option “–k 2” specifies second field for shorting. |
Numeric Sort (-n): If the file contains a numeric value and we want to perform shorting on a specific field contains numeric data then –n option is used.
Suppose we want to sort 3rd field of file Employee.txt contains numeric data the command is as follows:
1 | $ sort -t “|” -n -k 3 Employee.txt [press enter] |
Output
1 2 3 4 | Rajeev | CLERK | 300000 | 05-05-1987 | 31 | Manish | CA | 500000 | 10-02-1997 | 20 | Kumar | GM | 700000 | 05-02-1977 | 41 | Aditya | DGM | 100000 | 03-02-1987 | 30 | |
Reverse the Order (-r): Option –r is used to reverse the order of short option.
1 | $ sort -t “|” -r -k 2 Employee.txt [press enter] |
Other options of sort command:
[table id=8 /]