Shell细说sort排序

sort是在Linux里非常常用的一个命令,管排序

sort将文件的每一行作为一个单位,相互比较,比较原则是从首字符向后,依次按ASCII码值进行比较,最后将他们按升序输出。

使用方法:sort [选项]... [文件]...

长选项必须用的參数在使用短选项时也是必须的。顺序选项:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
-b, --ignore-leading-blanks ignore leading blanks
-d, --dictionary-order consider only blanks and alphanumeric characters
-f, --ignore-case fold lower case to upper case characters
-g, --general-numeric-sort compare according to general numerical value
-i, --ignore-nonprinting consider only printable characters
-M, --month-sort compare (unknown) < `JAN' < ... < `DEC'
-n, --numeric-sort compare according to string numerical value
-r, --reverse reverse the result of comparisons

Other options:

-c, --check check whether input is sorted; do not sort
-k, --key=POS1[,POS2] start a key at POS1, end it at POS2 (origin 1)
-m, --merge merge already sorted files; do not sort
-o, --output=FILE write result to FILE instead of standard output
-s, --stable stabilize sort by disabling last-resort comparison
-S, --buffer-size=SIZE use SIZE for main memory buffer
-t, --field-separator=SEP use SEP instead of non-blank to blank transition
-T, --temporary-directory=DIR use DIR for temporaries, not $TMPDIR or/tmp;
multiple options specify multiple directories
-u, --unique with -c, check for strict ordering;
without -c, output only the first of an equal run
-z, --zero-terminated end lines with 0 byte, not newline
--help 显示此帮助信息并退出
--version 输出版本号信息并退出
 
sort -u -r -o -n 选项基本用法

 

 pear由于重复被-u选项无情的删除了。

sort的-r选项

 

 sort的-o选项

由于sort默认是把结果输出到标准输出,所以需要用重定向才能将结果写入文件,形如sort oldfile > newfile
但是,如果你想把排序结果输出到原文件中,用重定向可就不行了。

[root@www ~]# sort -r sort.sh > sort.sh 
[root@www ~]# cat sort.sh 
[root@www ~]#

看,竟然将sort.sh清空了。

加上-o选项,解决了这个问题,让你放心的将结果写入原文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
[root@www ~]# cat sort.sh 
1
3
5
2
4
[root@www ~]# sort  -r sort.sh -o sort.sh 
[root@www ~]# cat sort.sh 
5
4

 

sort的-n选项

你有没有遇到过10比2小的情况。我反正遇到过。出现这种情况是由于排序程序将这些数字按字符来排序了,排序程序会先比较1和2,显然1小,所以就将10放在2前面喽。这也是sort的一贯作风。

我们如果想改变这种现状,就要使用-n选项,来告诉sort,“要以数值来排序”!

[root@www ~]# cat sort.sh 
1
10
19
11
2
5
[root@www ~]# sort sort.sh 
1
10
11
19
2
5
[root@www ~]# sort -n sort.sh 
1
2
5
10
11
19

sort的-t选项和-k选项

如果有一个文件的内容是这样:

1
2
3
4
5
[root@localhost ~]# cat facebook.txt 
banana:30:5.5
apple:10:2.5
pear:90:2.3
orange:20:3.4

这个文件有三列,列与列之间用冒号隔开了,第一列表示水果类型,第二列表示水果数量,第三列表示水果价格。

那么我想以水果数量来排序,也就是以第二列来排序,如何利用sort实现?

幸好,sort提供了-t选项,后面可以设定间隔符。(是不是想起了cut和paste的-d选项,共鸣~~)

指定了间隔符之后,就可以用-k来指定列数了。

[root@localhost ~]# sort -n -k 2 -t : facebook.txt 
apple:10:2.5
orange:20:3.4
banana:30:5.5
pear:90:2.3

参考文献:https://wenku.baidu.com/view/7453780f925f804d2b160b4e767f5acfa1c783e8.html

posted @ 2022-10-22 15:29  Harda  阅读(248)  评论(0编辑  收藏  举报