Linux comm命令求出文件的交集、差集
A(1,2,3)和B(3,4,5),A和B的交集是3,A对B的差集是1和2,B对A的差集是4和5,A和B求差的结果是1、2、4、5。
在Linux中可以使用comm命令求出这些集。
[root@xuexi tmp]# cat <<eof>set1.txt > orange > gold > apple > sliver > steel > iron > eof
[root@xuexi tmp]# cat <<eof>set2.txt > orange > gold > cookiee > carrot > eof
使用comm命令。
[root@xuexi tmp]# comm set1.txt set2.txt apple orange comm: file 1 is not in sorted order comm: file 2 is not in sorted order gold cookiee carrot silver steel iron
提示没有排序,所以comm必须要保证比较的文件是有序的。
[root@xuexi tmp]# sort set1.txt -o set1.txt;sort set2.txt -o set2.txt
[root@xuexi tmp]# comm set1.txt set2.txt
apple
carrot
cookiee
gold
iron
orange
silver
steel
结果中输出了3列,每一列使用制表符\t隔开。第一列是set1.txt中有而set2.txt中没有的,第二列则是set2.txt中有而set1.txt中没有的,第三列是set1.txt和set2.txt中都有的。
根据这三列就可以求出交集、差集和求差。
交集就是第三列。使用-1和-2分别删除第一第二列就是第三列的结果。
[root@xuexi tmp]# comm set1.txt set2.txt -1 -2 gold orange
A对B的差集就是第一列,B对A的差集就是第二列。
[root@xuexi tmp]# comm set1.txt set2.txt -2 -3 # A对B的差集 apple iron silver steel
[root@xuexi tmp]# comm set1.txt set2.txt -1 -3 # B对A的差集 carrot cookiee
A和B的求差就是第一列和第二列的组合。
[root@xuexi tmp]# comm set1.txt set2.txt -3 apple carrot cookiee iron silver steel
但是这样分两列的结果不方便查看,应该进行处理使它们显示在同一列上。
[root@xuexi tmp]# comm set1.txt set2.txt -3 | tr "\t" "\0" apple carrot cookiee iron silver steel
转载请注明出处:https://www.cnblogs.com/f-ck-need-u/p/7454694.html
如果觉得文章不错,不妨给个打赏,写作不易,各位的支持,能激发和鼓励我更大的写作热情。谢谢!

Linux系列文章:https://www.cnblogs.com/f-ck-need-u/p/7048359.html
Shell系列文章:https://www.cnblogs.com/f-ck-need-u/p/7048359.html
网站架构系列文章:http://www.cnblogs.com/f-ck-need-u/p/7576137.html
MySQL/MariaDB系列文章:https://www.cnblogs.com/f-ck-need-u/p/7586194.html
Perl系列:https://www.cnblogs.com/f-ck-need-u/p/9512185.html
Go系列:https://www.cnblogs.com/f-ck-need-u/p/9832538.html
Python系列:https://www.cnblogs.com/f-ck-need-u/p/9832640.html
Ruby系列:https://www.cnblogs.com/f-ck-need-u/p/10805545.html
操作系统系列:https://www.cnblogs.com/f-ck-need-u/p/10481466.html
精通awk系列:https://www.cnblogs.com/f-ck-need-u/p/12688355.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!