Linux sort Command
The Linux sort command is used to sort the contents of a text file.
sort can sort the contents of a text file line by line.
Syntax
sort [-bcdfimMnr][-o<output file>][-t<delimiter>][+<start field>-<end field>][--help][--version][file][-k field1[,field2]]
Parameter Description:
-b Ignore leading blank spaces in each line.
-c Check if the file is already sorted in order.
-d Sort, considering only letters, numbers, and spaces, ignoring other characters.
-f Treat lowercase letters as uppercase during sorting.
-i Ignore characters outside the ASCII range 040 to 176 during sorting.
-m Merge several sorted files.
-M Sort by the first three letters as month abbreviations.
-n Sort by numerical value.
-u Ensures uniqueness, outputting the result after removing duplicates.
-o<output file> Save the sorted result to the specified file.
-r Sort in reverse order.
-t<delimiter> Specify the field delimiter for sorting.
+<start field>-<end field> Sort by the specified fields, ranging from the start field to the field before the end field.
--help Display help.
--version Display version information.
[-k field1[,field2]] Sort by the specified columns.
Example
To sort the lines of a file using the default method with the sort command, use the following command:
sort testfile
The sort command will sort the first column of the text file in ASCII order by default and output the result to the standard output.
Using the cat command to display the testfile file shows the original order as follows:
$ cat testfile # Original order of testfile
test 30
Hello 95
Linux 85
The result after using the sort command is as follows:
$ sort testfile # Rearranged result
Hello 95
Linux 85
test 30
Using the -k
parameter to sort by the second column, the result is as follows:
$ sort testfile -k 2
test 30
Linux 85
Hello 95