工作原理:
Sort将文件的每一行作为一个单位,相互比较,比较原则是从首字符向后,依次按ASCII码值进行比较,最后将他们按升序输出。
-n:依照数值的大小排序;
-r:以相反的顺序来排序;
-t<分隔字符>:指定排序时所用的栏位分隔字符;
-k:指定需要排序的栏位
-u :忽略相同行
不加任何选项时,将对整行从第一个字符开始依次向后直到行尾按照默认的字符集排序规则做升序排序。
[root@centos7 ~]# cat b.txt | wc -l
13
[root@centos7 ~]#
[root@centos7 ~]# cat b.txt
1
2
3
3
4
4
4
2
2
5
5
6
3
[root@centos7 ~]# cat b.txt |sort
1
2
2
2
3
3
3
4
4
4
5
5
6
[root@centos7 ~]#
[root@centos7 ~]# uniq b.txt #uniq 默认对相邻的内容去重
1
2
3
4
2
5
6
3
[root@centos7 ~]# uniq b.txt |sort
1
2
2
3
3
4
5
6
[root@centos7 ~]#
[root@centos7 ~]# uniq -c b.txt
1 1
1 2
2 3
3 4
2 2
2 5
1 6
1 3
[root@centos7 ~]# uniq -c b.txt |sort
1 1
1 2
1 3
1 6
2 2
2 3
2 5
3 4
[root@centos7 ~]#
a: 只对相邻的相同内容去重
[root@centos7 ~]# cat c.txt
10.0.0.7
10.0.0.6
10.0.0.6
10.0.0.7
10.0.0.8
10.0.0.8
10.0.0.9
[root@centos7 ~]#
[root@centos7 ~]# cat c.txt |wc -l
7
[root@centos7 ~]#
[root@centos7 ~]# uniq c.txt
10.0.0.7
10.0.0.6
10.0.0.7
10.0.0.8
10.0.0.9
[root@centos7 ~]#
可通过sort配合完全去重;让重复的行相邻
[root@centos7 ~]# sort c.txt
10.0.0.6
10.0.0.6
10.0.0.7
10.0.0.7
10.0.0.8
10.0.0.8
10.0.0.9
[root@centos7 ~]#
[root@centos7 ~]# sort c.txt |uniq
10.0.0.6
10.0.0.7
10.0.0.8
10.0.0.9
[root@centos7 ~]#
[root@centos7 ~]# sort -u c.txt
10.0.0.6
10.0.0.7
10.0.0.8
10.0.0.9
[root@centos7 ~]#
将cc列数字从大到小顺序排列:
[root@centos7 ~]# cat b.txt
eee:40:5.4
eee:60:5.1
ddd:20:4.2
ccc:50:3.3
bbb:10:2.5
aaa:30:1.6
[root@centos7 ~]# sort b.txt
aaa:30:1.6
bbb:10:2.5
ccc:50:3.3
ddd:20:4.2
eee:40:5.4
eee:60:5.1
[root@centos7 ~]# sort -nrk 3 -t ':' b.txt
eee:40:5.4
eee:60:5.1
ddd:20:4.2
ccc:50:3.3
bbb:10:2.5
aaa:30:1.6
[root@centos7 ~]#
[root@centos7 ~]# cat aa.txt
1
11
2
3
4
5
78
[root@centos7 ~]#
[root@centos7 ~]# sort aa.txt
1
11
2
3
4
5
78
[root@centos7 ~]# sort -n aa.txt
1
2
3
4
5
11
78
[root@centos7 ~]#
[root@centos7 ~]# cat aa.txt
1 a
11 b
2 c
3 d
4 e
5 k
78 y
[root@centos7 ~]#
[root@centos7 ~]# sort -t ' ' -k2 aa.txt
1 a
11 b
2 c
3 d
4 e
5 k
78 y
[root@centos7 ~]#