sort 文本排序

本文介绍了如何使用`sort`命令对文本进行排序,特别是通过`-n`、`-t`、`-k`参数来指定按第三列和第四列的特定部分进行排序。
摘要由CSDN通过智能技术生成
  • 语法
sort [options] [file]
-n 按照数字大小进行排序
-r 倒序排列
-t指定分隔符
-k 

按指定区间排序

-k3和-k3,3的含义不同,如果不指定结尾会默认从3列开始到行尾

如果同一行需要按两列排序的话,必须指定结尾!

-b 忽略每行开头存在的空格
-u去除重复行

 sort -n -t. -k3,3 -k4.1,4.3 arp.txt 

-k3,3   从第三列起始到第三列结束

-k4.1,4.3 从第三列第一个字符到第三列第三个字符

逗号 , 连接的是字段

句号 . 连接的是字符

 

[root@localhost logs]# cat sort.txt 
10.10.10.4
10.10.10.4
10.10.10.4
10.10.10.4
10.10.10.5
10.10.10.5
10.10.10.8
10.10.10.4
[root@localhost logs]# sort sort.txt 
10.10.10.4
10.10.10.4
10.10.10.4
10.10.10.4
10.10.10.4
10.10.10.5                不加选项
10.10.10.5
10.10.10.8
[root@localhost logs]# sort -n sort.txt 
10.10.10.4
10.10.10.4
10.10.10.4
10.10.10.4
10.10.10.4
10.10.10.5
10.10.10.5               -n选项作用
10.10.10.8 
[root@localhost logs]# sort -nr sort.txt 
10.10.10.8
10.10.10.5
10.10.10.5
10.10.10.4
10.10.10.4
10.10.10.4                -r选项作用
10.10.10.4
10.10.10.4
[root@localhost logs]# sort -ur sort.txt  
10.10.10.8
10.10.10.5                -u选项作用
10.10.10.4
[root@localhost logs]# echo {a..z}
a b c d e f g h i j k l m n o p q r s t u v w x y z
[root@localhost logs]# cat test.txt 
10.10.10.4 r
10.10.10.4 g
10.10.10.4 a
10.10.10.5 n
10.10.10.4 q
10.10.10.8 l
[root@localhost logs]# sort test.txt 
10.10.10.4 a
10.10.10.4 g
10.10.10.4 q
10.10.10.4 r
10.10.10.5 n                 可以看出是先按数字然后按字母排序
10.10.10.8 l
[root@localhost logs]# sort -t " " -k2 test.txt 
10.10.10.4 a
10.10.10.4 g
10.10.10.8 l
10.10.10.5 n
10.10.10.4 q                 以空格为分隔符,以第二列进行排序
10.10.10.4 r
[root@localhost logs]# cat arp.txt 
192.168.111.1   00:50:56:c0:00:08
192.168.113.2   00:50:56:e7:84:7f
192.168.112.3   00:50:56:e7:84:72
192.168.111.2   00:50:56:e7:84:51
192.168.111.43  00:50:56:e7:84:6f
192.168.111.140 00:50:56:e7:84:3d
192.168.111.5   00:50:56:e7:84:09
192.168.111.6   00:50:56:e7:84:7a  
[root@localhost logs]# sort -n -t. -k3,3 -k4.1,4.3 arp.txt 
192.168.111.1   00:50:56:c0:00:08
192.168.111.2   00:50:56:e7:84:51
192.168.111.5   00:50:56:e7:84:09
192.168.111.6   00:50:56:e7:84:7a
192.168.111.43  00:50:56:e7:84:6f
192.168.111.140 00:50:56:e7:84:3d
192.168.112.3   00:50:56:e7:84:72             以第三列和第四列进行排序
192.168.113.2   00:50:56:e7:84:7f
[root@localhost logs]# sort -n -t. -k3 -k4.1,4.3 arp.txt   
192.168.111.1   00:50:56:c0:00:08
192.168.111.140 00:50:56:e7:84:3d
192.168.111.2   00:50:56:e7:84:51
192.168.111.43  00:50:56:e7:84:6f
192.168.111.5   00:50:56:e7:84:09
192.168.111.6   00:50:56:e7:84:7a
192.168.112.3   00:50:56:e7:84:72            在第三列的时候没有指定结尾,输出内容错误
192.168.113.2   00:50:56:e7:84:7f

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值