歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> Linux Shell 下求兩個文件交集和差集的辦法

Linux Shell 下求兩個文件交集和差集的辦法

日期:2017/3/1 10:22:19   编辑:SHELL編程

假設兩個文件FILE1和FILE2用集合A和B表示,FILE1內容如下:

  1. a
  2. b
  3. c
  4. e
  5. d
  6. a

FILE2內容如下:

  1. c
  2. d
  3. a
  4. 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。

直接運行結果如下:

  1. $ comm a.txt b.txt
  2. a
  3. b
  4. c
  5. d
  6. a
  7. c
  8. e
  9. d
  10. a

僅僅排序:

  1. $ comm <(sort a.txt ) <(sort b.txt )
  2. a
  3. a
  4. b
  5. c
  6. c
  7. d
  8. e

排序並且唯一:

  1. $ comm <(sort a.txt|uniq ) <(sort b.txt|uniq )
  2. a
  3. b
  4. c
  5. d
  6. e

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

  1. $ comm -12 <(sort a.txt|uniq ) <(sort b.txt|uniq )
  2. a
  3. c
  4. d

至於差集,讀者自己思考了。

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

  1. p$ grep -F -f a.txt b.txt
  2. c
  3. d
  4. a
  5. c

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

  1. $ grep -F -f a.txt b.txt | sort | uniq
  2. a
  3. c
  4. d

差集呢?

  1. $ grep -F -v -f a.txt b.txt | sort | uniq
  2. $ grep -F -v -f b.txt a.txt | sort | uniq
  3. b
  4. e

第一行結果為B-A,所以為空;第二行為A-B。注意順序很重要!

Copyright © Linux教程網 All Rights Reserved