一、交集
sort a.txt b.txt | uniq -d
二、並集
sort a.txt b.txt | uniq
三、差集
a.txt-b.txt:
sort a.txt b.txt b.txt | uniq -u
b.txt - a.txt:
sort b.txt a.txt a.txt | uniq -u
四、相關的解釋
使用sort可以將文件進行排序(sort排序是為了管道交給uniq進行處理,uniq只能處理相鄰的行),可以使用sort后面的參數,例如 -n 按照數字格式排序,例如 -i 忽略大小寫,例如使用-r 為逆序輸出等
uniq為刪除文件中重復的行,得到文件中唯一的行,參數-d 表示的是輸出出現次數大於1的內容;參數-u表示的是輸出出現次數為1的內容;那么對於上述的求交集並集差集的命令做如下的解釋:
sort a.txt b.txt | uniq -d:將兩個文件進行排序,uniq使得兩個文件中的內容為唯一的,使用-d輸出兩個文件中次數大於1的內容,即是得到交集
sort a.txt b.txt | uniq :將兩個文件進行排序,uniq使得兩個文件中的內容為唯一的,即可得到兩個文件的並集
sort a.txt b.txt b.txt | uniq -u:將兩個文件排序,最后輸出a.txt b.txt b.txt文件中只出現過一次的內容,因為有兩個b.txt所以只會輸出只在a.txt出現過一次的內容(b.txt的內容至少出現兩次),即是a.txt-b.txt差集;對於b.txt-a.txt同理。
樣例
# a.hosts
[root(0)@thatsit 11:40:46 ~/scripts]# cat a.hosts 10.10.1.101 10.10.1.102 10.10.1.103 10.10.1.104 [root(0)@thatsit 11:40:47 ~/scripts]#
# b.hosts
[root(0)@thatsit 11:40:48 ~/scripts]# cat b.hosts 10.10.1.101 10.10.1.103 10.10.1.105 [root(0)@thatsit 11:40:49 ~/scripts]#
# a.hosts ∩ b.hosts
[root(0)@thatsit 11:40:49 ~/scripts]# sort a.hosts b.hosts | uniq -d 10.10.1.101 10.10.1.103 [root(0)@thatsit 11:41:08 ~/scripts]#
# a.hosts ∪ b.hosts
[root(0)@thatsit 11:41:10 ~/scripts]# sort a.hosts b.hosts | uniq 10.10.1.101 10.10.1.102 10.10.1.103 10.10.1.104 10.10.1.105 [root(0)@thatsit 11:41:19 ~/scripts]#
# a.hosts - b.hosts
[root(0)@thatsit 11:41:25 ~/scripts]# sort a.hosts b.hosts b.hosts | uniq -u 10.10.1.102 10.10.1.104 [root(0)@thatsit 11:41:45 ~/scripts]#
# b.hosts - a.hosts
[root(0)@thatsit 11:41:47 ~/scripts]# sort a.hosts a.hosts b.hosts | uniq -u 10.10.1.105 [root(0)@thatsit 11:41:55 ~/scripts]#