2016-08-04 36 views
0

我需要小小的幫助。解析來自兩列文件的行

我想從以下兩個文件行(剛剛從第二個文件),其中第二列是相同的,但theit第一列是唯一在bash解析:

file1 
111403787651,111915870316631 
111408649892,111917070744403 
111408653841,111919750018614 
111408655467,111917420005028 

file2 
111403787651,111915870316631 
444444444441,111917070744403 
222222222222,333333333333333 

輸出: 剛剛從第二個文件

444444444441,111917070744403 

感謝

+0

文件1中的數據是否具有「111,222」和「112,222」形式的條目(相同的第二列值,不同的列1值)? –

+0

「第二列是相同的」意味着什麼,到底是什麼? 「在第一個文件中找到第二列的位置」?同樣,「第一列唯一」是指「第一列*不在第一個文件中找到」? –

+0

...第一個文件中第一列和第二列之間的配對是否有任何作用,或者每個列的順序是否可以完全隨機化而不改變輸出? –

回答

1

awk來救援!

$ awk -F, 'NR==FNR{a[$2]=$1; next} $2 in a && $1 != a[$2]' file1 file2 
444444444441,111917070744403 
0

假設我正確地讀出你的意圖(一個大的前提,作爲問題的語言在很大程度上是不精確),以下是本機的bash實現無需外部工具,併發出所需的輸出鑑於問題的輸入:

#!/bin/bash 
#  ^^^^ - NOT /bin/sh, as this requires bash-only (indeed, bash-4.x+-only) features 

# read first file's contents 
declare -A first=() second=() # define associative arrays; requires bash 4.0 
while IFS=, read -r a b; do  # read columns into variables a and b 
    first[$a]=1; second[$b]=1  # set associative-array keys for each 
done <file1      # ...doing the above reading from file1 

# iterate through second file's contents 
while IFS=, read -r a b; do  # again, read into a and b 
    if [[ ${second[$b]} && ! ${first[$a]} ]]; then # if we already saw b, and did not see a 
    printf '%s,%s\n' "$a" "$b"     # ...then emit output. 
    fi 
done <file2      # ...doing the above reading from file2 

參考文獻:

  • BashFAQ #001 (「我怎樣才能逐行讀取文件(數據流,變量)?」)
  • BashFAQ #006(「我怎樣才能使用關聯數組?」)
+1

這和@ karakfa的awk答案之間有趣的功能區別在於w,x和y,z出現在file1中,w和z出現在file2中。 awk腳本將輸出w,z,而bash腳本不會,因爲awk腳本要求第一個字段與file1中的第二個字段值相關聯,而bash腳本只需要第一個字段存在於任何第二個字段值在file1中。太糟糕了,OP沒有在他們的樣本輸入/輸出中包括這種情況,所以我們知道他們想要什麼。我總是很驚訝於這些例子中的一點思考...... :-(。 –