LINUX Shell 下求两个文件交集和差集的办法

假设两个文件FILE1和FILE2用集合A和B表示,FILE1内容如下:

FILE2内容如下:

基本上有两个方法,一个是comm命令,一个是grep命令。分别介绍如下:

comm命令 , Compare sorted files FILE1 and FILE2 line by line. With  no options, produce three-column output.  Column one contains lines unique to FILE1, column two contains lines unique to FILE2, and column three contains lines common to both files. 要注意两个文件必须是排序和唯一(sorted and unique)的,默认输出为三列,第一列为是A-B,第二列B-A,第三列为A交B。

直接运行结果如下:

仅仅排序:

排序并且唯一:

如果只想要交集,如下即可:

至于差集,读者自己思考了。

grep 命令是常用的搜索文本内容的,要找交集,如下即可:

grep不要求排序,但是因为是集合操作,唯一是必须的(不然怎么是集合呢?)。所以:

差集呢?

第一行结果为B-A,所以为空;第二行为A-B。注意顺序很重要!

原文地址:https://www.cnblogs.com/ainima/p/6331310.html