Linux 对比两个文本的交集和差集(comm)

时间:2022-05-19 15:25:05

200 ? "200px" : this.width)!important;}
-->

介绍

comm命令可以对两个已排序好的文本的内容进行交集和差集的对比,记住必须是已排序过的文件;可以使用sort命令对没有排序的文件进行排序,comm命令在对比结果中会产生三列分别是:在A中不在B中的内容,在B中不在A中的内容,AB的交集的内容。

事例

[root@localhost test]# cat a
c
b
a [root@localhost test]# cat b
b
c
d

其中文件a不是倒序的文件,看看直接拿来对比会出现什么问题。

[root@localhost test]# comm a b
b
c
comm: file is not in sorted order
b
a d

对比结果出现了问题提示文件1不是已排序的文件。

1.对文件进行排序

[root@localhost test]# sort a -o a
[root@localhost test]# cat a
a
b
c

2.对比文件

[root@localhost test]# comm a b
a
b
c
d

第一列:在a文件中不在b文件中的内容

第二列:在b文件中不在a文件中的内容

第三列:a文件和b文件的交集

comm命令参数

-1:不显示第一列

-2:不显示第二列

-3:不显示第三列

[root@localhost test]# comm a b -
b
c
d
[root@localhost test]# comm a b -
a
b
c
[root@localhost test]# comm a b -
a
d
[root@localhost test]# comm a b -
b
c

其它的一些特殊处理方法

[root@localhost test]# comm a b -
a
d
[root@localhost test]# comm a b - | sed 's/^\t//'
a
d

可以使用sed命令将开头的制表符(tab)替换掉,s:替换的意思,^:以什么开头,\t:制表符,//:空

总结

备注:

作者:pursuer.chen

博客:http://www.cnblogs.com/chenmh

本站点所有随笔都是原创,欢迎大家转载;但转载时必须注明文章来源,且在文章开头明显处给明链接。

《欢迎交流讨论》