shell的sort命令

sort命令以行为单位对文本进行排序。

命令语法:

sort [-b/d/f/g/i/M/n/r] [InFile]

参数解释:

-b: ignore-leading-blanks,忽略前面空格符部分
-d: data-order,仅考虑空格和字母数字字符
-f: ignore-case,忽略大小写
-g: general-numeric-sort,根据一般数值进行排序
-i: ignore-nonprinting,忽略不可打印的字符,比如换行符、回车符
-M: month-sort,以月份进行排序
-n: numeric-sort,根据字符串数值进行排序
-r: reverse,反向输出排序结果

其他参数:

-c: check,检查文本是否已排序,如果不是,则输出第一个乱序的行的相关信息,返回1
-k N: key,以第N列进行排序
-m S1 S2: merge,合并已排序的S1、S2文本,不再排序
-o File: output,将结果写入File中
-s: stable,通过禁用最后的比较来稳定排序
-t sep: field-separator,使用sep作为分隔符来区分列
-u: unique,去掉重复的行
-z: 零终止的结束行,0字节,而不是换行符

栗子

# sort.txt

1
mac 2000 3 winxp 4000 2 linux 1000 4 win7 1000 2 linux 1000

1. 以数字进行排序

1) - n

sort -n sort.txt 

结果为:

1 mac 2000
2 linux 1000
2 linux 1000
3 winxp 4000
4 win7 1000

2) - g

sort -g sort.txt

结果为:

1 mac 2000
2 linux 1000
2 linux 1000
3 winxp 4000
4 win7 1000

2. 反向排序

sort -r  sort.txt 

结果为:

4 win7 1000
3 winxp 4000
2 linux 1000
2 linux 1000
1 mac 2000

3. 以指定列进行排序(以下为第三列)

sort -k 3 sort.txt 

结果为:

2 linux 1000
2 linux 1000
4 win7 1000
1 mac 2000
3 winxp 4000

4.排序结果去除重复的行

 sort -u sort.txt 

结果为:

1 mac 2000
2 linux 1000
3 winxp 4000
4 win7 1000

5.合并两个已排序的文本

sort -m sort.txt uniq.txt

只是单纯的合并,不会进行排序

 

posted @ 2018-11-14 10:58  傲娇的草履虫  阅读(7764)  评论(0编辑  收藏  举报