LINUX Shell 下求两个文件交集和差集的办法
2014-12-01 16:45
701 查看
/article/1709736.html
假设两个文件FILE1和FILE2用集合A和B表示,FILE1内容如下:
[xhtml] view plaincopy
a
b
c
e
d
a
FILE2内容如下:
[xhtml] view plaincopy
c
d
a
c
基本上有两个方法,一个是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。
直接运行结果如下:
[xhtml] view plaincopy
$ comm a.txt b.txt
a
b
c
d
a
c
e
d
a
仅仅排序:
[xhtml] view plaincopy
$ comm <(sort a.txt ) <(sort b.txt )
a
a
b
c
c
d
e
排序并且唯一:
[xhtml] view plaincopy
$ comm <(sort a.txt|uniq ) <(sort b.txt|uniq )
a
b
c
d
e
如果只想要交集,如下即可:
[xhtml] view plaincopy
$ comm -12 <(sort a.txt|uniq ) <(sort b.txt|uniq )
a
c
d
至于差集,读者自己思考了。
grep 命令是常用的搜索文本内容的,要找交集,如下即可:
[xhtml] view plaincopy
p$ grep -F -f a.txt b.txt
c
d
a
c
grep不要求排序,但是因为是集合操作,唯一是必须的(不然怎么是集合呢?)。所以:
[c-sharp] view plaincopy
$ grep -F -f a.txt b.txt | sort | uniq
a
c
d
差集呢?
[xhtml] view plaincopy
$ grep -F -v -f a.txt b.txt | sort | uniq
$ grep -F -v -f b.txt a.txt | sort | uniq
b
e
第一行结果为B-A,所以为空;第二行为A-B。注意顺序很重要!
假设两个文件FILE1和FILE2用集合A和B表示,FILE1内容如下:
[xhtml] view plaincopy
a
b
c
e
d
a
FILE2内容如下:
[xhtml] view plaincopy
c
d
a
c
基本上有两个方法,一个是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。
直接运行结果如下:
[xhtml] view plaincopy
$ comm a.txt b.txt
a
b
c
d
a
c
e
d
a
仅仅排序:
[xhtml] view plaincopy
$ comm <(sort a.txt ) <(sort b.txt )
a
a
b
c
c
d
e
排序并且唯一:
[xhtml] view plaincopy
$ comm <(sort a.txt|uniq ) <(sort b.txt|uniq )
a
b
c
d
e
如果只想要交集,如下即可:
[xhtml] view plaincopy
$ comm -12 <(sort a.txt|uniq ) <(sort b.txt|uniq )
a
c
d
至于差集,读者自己思考了。
grep 命令是常用的搜索文本内容的,要找交集,如下即可:
[xhtml] view plaincopy
p$ grep -F -f a.txt b.txt
c
d
a
c
grep不要求排序,但是因为是集合操作,唯一是必须的(不然怎么是集合呢?)。所以:
[c-sharp] view plaincopy
$ grep -F -f a.txt b.txt | sort | uniq
a
c
d
差集呢?
[xhtml] view plaincopy
$ grep -F -v -f a.txt b.txt | sort | uniq
$ grep -F -v -f b.txt a.txt | sort | uniq
b
e
第一行结果为B-A,所以为空;第二行为A-B。注意顺序很重要!
相关文章推荐
- 【转】LINUX Shell 下求两个文件交集和差集的办法
- LINUX Shell 下求两个文件交集和差集的办法
- LINUX Shell 下求两个文件交集和差集的办法
- Linux shell计算两个文件的交集,并集和差集
- Linux Shell下求两个文件的交集差集
- 如何求两个文件的交集、并集和差集?------sort和uniq闪亮登场
- linux求两个文件的交集,并集,差集
- Linux 两个文件求交集、并集、差集
- linux shell下求文件的交集、并集、差集
- linux命令求两个文件的交集、差集、并集等
- 利用sort和uniq求两个文件的并集,交集和差集
- Linux 两个文件求交集、并集、差集
- uniq 求两个文件的交集,并集,差集
- linux shell 脚本攻略学习10--生成任意大小的文件和文本文件的交集与差集详解
- 关于Hibernate自动生成表的实体类时,出现两个java文件的解决办法
- js取数组两个数组的交集|差集|并集|补集|去重
- Shell 取两个文件的交集和并集
- 输入两个闭区间,求其交集,并集和差集(C++):
- C# 两个datatable中的数据快速比较返回交集或差集
- shell中使用sort和uniq实现两文件的并集,交集和差集