Linuxstar
Published on

sort command-sort files and output

Jonas

Jonas

2 min read
The sort command is very useful in Linux. It sorts files and outputs the sorted result to the standard. The sort command can either get input from a specific file or from stdin.

Syntax:

sort [parameter] [file]

Command parameters:

-b Ignore the space characters at the beginning of each line
-c Check if the files are sorted in order
-d When sorting, deal with English letters, numbers and space characters, ignore other characters
-f When sorting, treat lowercase letters as uppercase letters
-i When sorting, except ASCII characters between 040 and 176, other characters are ignored
-m Combine files with several sort numbers
-M Sort the first 3 letters according to the abbreviation of the month
-n Sort by value
-o <output file> Save the sorted results into the specified file
-r Sort in reverse order
-t <separation character> Specify the field separator character used when sorting
-k Specify the field to be sorted

Example

Sort takes each line of the file/text as a unit and compares each other. The comparison principle is to compare the ASCII code values ​​from the first character to the back, and finally output them in ascending order:
[root@linuxstar ~]# cat sort.txt  AA:10:1.1 CC:30:3.3 DD:40:4.4 BB:20:2.2 FF:60:6.6 FF:60:6.6 EE:50:5.5 
[root@linuxstar ~]# sort sort.txt  AA:10:1.1 BB:20:2.2 CC:30:3.3 DD:40:4.4 EE:50:5.5 FF:60:6.6 FF:60:6.6
Ignore the same line and use the -u option or uniq:
[root@linuxstar ~]# cat sort.txt  AA:10:1.1 CC:30:3.3 DD:40:4.4 BB:20:2.2 FF:60:6.6 FF:60:6.6 EE:50:5.5 [root@linuxstar ~]# sort -u sort.txt  AA:10:1.1 BB:20:2.2 CC:30:3.3 DD:40:4.4 EE:50:5.5 FF:60:6.6 [root@linuxstar ~]# uniq sort.txt  AA:10:1.1 CC:30:3.3 DD:40:4.4 BB:20:2.2 FF:60:6.6 EE:50:5.5
Use of sort's -n, -r, -k, and -t options:
[root@linuxstar ~]# cat sort.txt  AA:BB:CC aa:30:1.9 cc:50:3.3 dd:20:4.2 bb:10:2.4 ee:40:5.3 ee:60:5.1 
[root@linuxstar ~]# sort -nk 2 -t: sort.txt AA:BB:CC bb:10:2.4 dd:20:4.2 aa:30:1.9 ee:40:5.3 cc:50:3.3 ee:60:5.1 
[root@linuxstar ~]# sort -nrk 3 -t: sort.txt ee:40:5.3 ee:60:5.1 dd:20:4.2 cc:50:3.3 bb:10:2.4 aa:30:1.9 AA:BB:CC