求两个Linux文本文件的交集、差集、并集

 

一、交集

sort a.txt b.txt | uniq -d

二、并集

sort a.txt b.txt | uniq

三、差集

a.txt-b.txt:

sort a.txt b.txt b.txt | uniq -u

b.txt - a.txt:

sort b.txt a.txt a.txt | uniq -u

四、相关的解释

使用sort可以将文件进行排序(sort排序是为了管道交给uniq进行处理,uniq只能处理相邻的行),可以使用sort后面的参数,例如 -n 按照数字格式排序,例如 -i 忽略大小写,例如使用-r 为逆序输出等

uniq为删除文件中重复的行,得到文件中唯一的行,参数-d 表示的是输出出现次数大于1的内容;参数-u表示的是输出出现次数为1的内容;那么对于上述的求交集并集差集的命令做如下的解释:

sort a.txt b.txt | uniq -d:将两个文件进行排序,uniq使得两个文件中的内容为唯一的,使用-d输出两个文件中次数大于1的内容,即是得到交集

sort a.txt b.txt | uniq :将两个文件进行排序,uniq使得两个文件中的内容为唯一的,即可得到两个文件的并集

sort a.txt b.txt b.txt | uniq -u:将两个文件排序,最后输出a.txt b.txt b.txt文件中只出现过一次的内容,因为有两个b.txt所以只会输出只在a.txt出现过一次的内容(b.txt的内容至少出现两次),即是a.txt-b.txt差集;对于b.txt-a.txt同理。

样例

# a.hosts

[root(0)@thatsit 11:40:46 ~/scripts]# cat a.hosts

10.10.1.101

10.10.1.102

10.10.1.103

10.10.1.104

[root(0)@thatsit 11:40:47 ~/scripts]#

# b.hosts

[root(0)@thatsit 11:40:48 ~/scripts]# cat b.hosts

10.10.1.101

10.10.1.103

10.10.1.105

[root(0)@thatsit 11:40:49 ~/scripts]#

# a.hosts ∩ b.hosts

[root(0)@thatsit 11:40:49 ~/scripts]# sort a.hosts b.hosts | uniq -d

10.10.1.101

10.10.1.103

[root(0)@thatsit 11:41:08 ~/scripts]# 

# a.hosts ∪ b.hosts

[root(0)@thatsit 11:41:10 ~/scripts]# sort a.hosts b.hosts | uniq

10.10.1.101

10.10.1.102

10.10.1.103

10.10.1.104

10.10.1.105

[root(0)@thatsit 11:41:19 ~/scripts]#

# a.hosts - b.hosts

[root(0)@thatsit 11:41:25 ~/scripts]# sort a.hosts b.hosts b.hosts | uniq -u

10.10.1.102

10.10.1.104

[root(0)@thatsit 11:41:45 ~/scripts]#

# b.hosts - a.hosts 

[root(0)@thatsit 11:41:47 ~/scripts]# sort a.hosts a.hosts b.hosts | uniq -u

10.10.1.105

[root(0)@thatsit 11:41:55 ~/scripts]#

  

参考链接:http://www.cnblogs.com/molong1208/p/5358509.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值