如何取两个文本的交集
时间:2009-05-07 来源:风山渐
工作中需要找出两个文本的交集的字符,两个文本里面的内容都是一行一行的userid。
[oracle@db-1 ~]$ more *.txt
::::::::::::::
s.txt
::::::::::::::
1
2
3
4
6 ::::::::::::::
t.txt
::::::::::::::
5
7
1
2
3 一开始使用comm命令 比如下面命令本来是希望找出只出现在t.txt而不出现在s.txt中的字符: [oracle@db-1 ~]$ comm -13 s.txt t.txt
5
7
1
2
3 显然,上面并不是我想要的结果。 下面的命令是想找出s.txt和t.txt的交集: [oracle@db-1 ~]$ comm -12 s.txt t.txt 这次没有结果输出。 Google后发现comm对字符串的位置敏感,需要一一对应。 解决的方法是使用sort [oracle@db-1 ~]$ sort -m <(sort s.txt |uniq) <(sort t.txt |uniq) |uniq -d
1
2
3 ------------------------------------ 取两个文本的并、交、差集
并:sort -m <(sort file1 | uniq) <(sort file2 | uniq) | uniq
交:sort -m <(sort file1 | uniq) <(sort file2 | uniq) | uniq -d
差:sort -m <(sort file1 | uniq) <(sort file2 | uniq) <(sort file2 | uniq) | uniq -u
::::::::::::::
s.txt
::::::::::::::
1
2
3
4
6 ::::::::::::::
t.txt
::::::::::::::
5
7
1
2
3 一开始使用comm命令 比如下面命令本来是希望找出只出现在t.txt而不出现在s.txt中的字符: [oracle@db-1 ~]$ comm -13 s.txt t.txt
5
7
1
2
3 显然,上面并不是我想要的结果。 下面的命令是想找出s.txt和t.txt的交集: [oracle@db-1 ~]$ comm -12 s.txt t.txt 这次没有结果输出。 Google后发现comm对字符串的位置敏感,需要一一对应。 解决的方法是使用sort [oracle@db-1 ~]$ sort -m <(sort s.txt |uniq) <(sort t.txt |uniq) |uniq -d
1
2
3 ------------------------------------ 取两个文本的并、交、差集
并:sort -m <(sort file1 | uniq) <(sort file2 | uniq) | uniq
交:sort -m <(sort file1 | uniq) <(sort file2 | uniq) | uniq -d
差:sort -m <(sort file1 | uniq) <(sort file2 | uniq) <(sort file2 | uniq) | uniq -u
相关阅读 更多 +