Linux中sort命令

时间:2014-09-21 21:56:21   收藏:0   阅读:398

Linux sort命令用于将文本文件内容按某种方式排序,默认是ASCII码方式:

语法说明:

常用参数:

常用例子:

[root@host ~]# cat file
Unix
Linux
Solaris
AIX
Linux
HPUX
[root@host ~]# sort file      #默认按照ascii排序
AIX
HPUX
Linux
Linux
Solaris
Unix

[root@host ~]# cat file
Unix
Linux
Solaris
AIX
Linux
HPUX
[root@host ~]# sort -u file    #排除重复行
AIX
HPUX
Linux
Solaris
Unix
[root@host ~]# cat file
20
19
5
49
200
[root@host ~]# sort file #一般排序
19
20
200
49
5
#注意是首字母1..10来排序,这一般不是我们想要的.
[root@host ~]# cat file
20
19
5
49
200
#按数字自然顺序来排序
[root@host ~]# sort -n file
5
19
20
49
200
[root@host ~]# cat file
20
19
5
49
200
#按数字倒排序
[root@host ~]# sort -nr file
200
49
20
19
5
[root@host ~]# cat file1
20
19
5
49
200
[root@host ~]# cat file2
25
25
18
5
48
200

#按照自然顺序倒排序并移掉重复项
[root@host ~]# sort -nr -u file1 file2
200
49
48
25
20
19
18
5
[root@host ~]# cat file
Aug 8 30
Jan 1 31
Mar 3 31
Feb 2 28
May 5 30
Jul 7 31
Jun 6 30
[root@host ~]# sort -M file
Jan 1 31
Feb 2 28
Mar 3 31
May 5 30
Jun 6 30
Jul 7 31
Aug 8 30

[root@host ~]# cat file
Linux,20
Unix,30
AIX,25
Linux,25
Solaris,10
HPUX,100
# -t',' 以逗号分隔,也可以用""
# -k1,1 Form Field 1 to Field 1, 常用的用法,也就是按第一列排序
[root@host ~]# sort -t',' -k1,1 file
AIX,25
HPUX,100
Linux,20
Linux,25
Solaris,10
Unix,30
[root@host ~]# cat file
Linux,20
Unix,30
AIX,25
Linux,25
Solaris,10
HPUX,100
#-k2n 第二列按自然数排序
[root@host ~]# sort -t"," -k2n,2 -u file
Solaris,10
Linux,20
AIX,25
Linux,25
Unix,30
HPUX,100
#Linux,25这一行就会被移除
[root@host ~]# cat file
Linux,20
Unix,30
AIX,25
Linux,25
Solaris,10
HPUX,100
#-k 1,1 也可以分开来写
#-knr,2 也可以拆开来写 -k2,2 -nr
[root@host ~]# sort -t',' -k1,1 -k2nr,2 file
AIX,25
HPUX,100
Linux,25
Linux,20
Solaris,10
Unix,30
[root@host ~]# cat file
google 110 5000
baidu 100 5000
guge 50 3000
sohu 100 4500
#-t' ',默认是按空格,Tab键来排序,所以此处可以不要,只是为了好理解些
#-k 1.2,1.2 from 1 to 1,也就是按第一列来排序
#1.2表示第一列,第二个字符.  
#-k 3,3nr 第三列按自然数字倒序.注意其表现形式
[root@host ~] sort -t' ' -k 1.2,1.2 -k 3,3nr file
baidu 100 5000
google 110 5000
sohu 100 4500
guge 50 3000

Note:

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!