2016-08-03 68 views

回答

3

[ awk ]是你的朋友

awk 'NR==FNR{f[$1];next}{if($1 in f){next}else{print}}' A.txt B.txt 

或者更簡單地說

awk 'NR==FNR{f[$1];next}!($1 in f){print}' A.txt B.txt 

,甚至更簡單

awk 'NR==FNR{f[$1];next}!($1 in f)' A.txt B.txt 

的解釋有點C會不會ertainly幫助

  1. NR & FNR是AWK內置其中代表total number of records - including current - processed so fartotal number of records - including current - processed so far in the current file分別變量,它們將只對處理的第一個文件相同。

  2. f[$1]首先創建數組f,然後將$1作爲密鑰添加,如果相同的密鑰尚不存在。如果沒有賦值,那麼f [$ 1]會自動初始化爲0,但是這方面沒有在您的案例中找到用處

  3. next轉到下一條記錄,而沒有處理awk腳本的其餘部分。

  4. 請注意{if($1 in f){next}else{print}}部分將僅針對第二個(及其後的文件)進行處理。
  5. $1 in f檢查該鍵$1存在陣列f
  6. if-else-print部分是自解釋的。
  7. 注意在第三個版本中,{print}被省略,因爲awk的默認動作是打印!

+1

或者更簡單地'的awk「NR == FNR { f [$ 1];下一個}!(f中$ 1)'' – 123

+0

@ 123:我敢打賭,你很擅長這個.. :) Thankyou會將它添加到解決方案中 – sjsam

0

這樣在bash,但只有當你真的在第二列在所有感興趣:

diff <(cut -f1 -d" " A.txt) <(cut -f1 -d" " B.txt) 
2
awk 'NR==FNR{array[$1];next} !($1 in array)' a.txt b.txt 
3 B3