sort 功能说明:sort 命令将输入的文件内容按照指定的规则进行排序,然后将排序结果输出。
参数选项:
-b 忽略每行开头存在的空格字符。
-n 依照数值的大小进行排序。
-r 倒叙排列。
-u 去除重复行。
-t 指定分隔符。
-k 按指定区间排序。
默认是以行为单位进行比较
[root@testdb ~]# cat test.log
10.0.0.4
10.0.0.5
10.10.0.8
10.0.0.4
10.0.0.5
10.10.0.8
[root@testdb ~]# sort test.log
10.0.0.4
10.0.0.4
10.0.0.5
10.0.0.5
10.10.0.8
10.10.0.8
按照数字从小到大的顺序进行排列
[root@testdb ~]# sort -n test.log
10.0.0.4
10.0.0.4
10.0.0.5
10.0.0.5
10.10.0.8
10.10.0.8
输出按照降序排列
[root@testdb ~]# sort -nr test.log
10.10.0.8
10.10.0.8
10.0.0.5
10.0.0.5
10.0.0.4
10.0.0.4
去除重复行
[root@testdb ~]# sort -u test.log
10.0.0.4
10.0.0.5
10.10.0.8
通过参数-t、-k指定列排序
[root@testdb ~]# cat test.log
10.0.0.4 r
10.0.0.5 g
10.0.0.8 a
10.0.0.4 n
10.0.0.5 q
10.0.0.8 l
[root@testdb ~]# sort test.log # 默认是按照第一列排序
10.0.0.4 n
10.0.0.4 r
10.0.0.5 g
10.0.0.5 q
10.0.0.8 a
10.0.0.8 l
[root@testdb ~]# sort -t " " -k2 test.log
10.0.0.8 a
10.0.0.5 g
10.0.0.8 l
10.0.0.4 n
10.0.0.5 q
10.0.0.4 r
先按照IP地址的第3列排序,再按照IP地址的第4列排序
[root@testdb ~]# cat test.log
192.168.56.129 00:0c:29:fe:b6:9d
192.168.56.122 00:50:56:84:5b:06
192.168.56.76 00:0c:29:2f:0c:3c
192.168.56.92 00:0c:29:de:7e:3c
192.168.56.61 00:0c:29:58:48:4e
192.168.56.178 00:0c:29:34:d1:2f
192.168.56.47 00:0c:29:61:0b:6c
192.168.56.63 00:0c:29:dc:16:df
192.168.56.16 00:0c:29:99:b5:80
[root@testdb ~]#
[root@testdb ~]# sort -n -t. -k3,3 -k4.1,4.3 test.log
192.168.56.16 00:0c:29:99:b5:80
192.168.56.47 00:0c:29:61:0b:6c
192.168.56.61 00:0c:29:58:48:4e
192.168.56.63 00:0c:29:dc:16:df
192.168.56.76 00:0c:29:2f:0c:3c
192.168.56.92 00:0c:29:de:7e:3c
192.168.56.122 00:50:56:84:5b:06
192.168.56.129 00:0c:29:fe:b6:9d
192.168.56.178 00:0c:29:34:d1:2f
说明:
-n: 按照数字排序
-t.: 按照"."作为分隔域
-k3,3: 按照第3个字段开始到第3个字段结束排序
-k4.1,4.3: 按照第4个字段第1个字符开始到第4个字段第3个字符结束排序
".": 点号连接的是字符
",": 逗号连接的是字段