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<输出文件>][-t<分隔字符>][+<起始栏位>-<结束栏位>][--help][--verison][文件][-k field1[,field2]]
Parameter Description:
- -b Ignore leading whitespace characters at the beginning of each line.
- -c Check whether the file is already sorted.
- -d When sorting, ignore all characters except letters, digits, and whitespace.
- -f When sorting, treat lowercase letters as uppercase.
- -i When sorting, ignore all characters except ASCII characters between 040 and 176.
- -m Merge several already sorted files.
- -M Sort by the first three letters according to month abbreviations.
- -n Sort by numerical value.
- -u Means unique; the output has duplicates removed.
- -o
- -r Sort in reverse order.
- -t
Specify the field separator used for sorting. - +
- 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 column.
Example
To sort the lines of a file with the sort command using the default method, use the following command:
sort testfile
The sort command sorts the first column of a text file in ASCII order by default and outputs the result to standard output.
Using the cat command to display the testfile shows its original order as follows:
$ cat testfile # testfile文件原有排序
test 30
Hello 95
Linux 85
The result after reordering with the sort command is as follows:
$ sort testfile # 重排结果
Hello 95
Linux 85
test 30
Using the -k parameter to sort by the values in the second column gives the following result:
$ sort testfile -k 2
test 30
Linux 85
Hello 95
Linux Command Reference