2017-04-20 52 views
1

兩個文件,我需要根據三列的值,加入他們的行列,如果沒有匹配的打印NA,不匹配列。加入基於我有以下兩個文件三列

cat f1 
AAA 0 node4 Activated Unreachable down 
AAA 1 node3 Activated Pingable  cool 

cat f2 
AAA 0 node3 XYZ Active 

目前我正在使用不正確的輸出:

awk 'NR==FNR{a[$1]=$1;b[$2]=$2;c[$3]=$3;next} $1 in a && $2 in b && $3 in c{print $0}' f1 f2 
AAA 0 node3 XYZ Active 

所需的輸出:

AAA 0 node4 Activated Unreachable down NA 
AAA 1 node3 Activated Pingable cool Active 

回答

1

AWK方法:

awk 'NR==FNR{a[$1,$3]=$5; next}{$7="NA";if(($1,$3) in a){$7=a[$1,$3]} print}' f2 f1 

輸出:

AAA 0 node4 Activated Unreachable down NA 
AAA 1 node3 Activated Pingable cool Active 

a[$1,$3]=$5 - 存儲所述第五字段$5的在第二個文件f2使用第一組合的值$1和T希爾德$3領域陣列鍵

$7="NA"; - 發起附加第七字段$7與默認值「NA」

1

使用如下的Awk邏輯,

awk 'FNR==NR{hash[$1FS$3]=$NF; next}{for(i in hash) if (match(i,$1FS$3)) { $(NF+1)=hash[i] } else { $(NF+1)="NA" } }1' f2 f1 

產生輸出你需要。

AAA 0 node4 Activated Unreachable down NA 
AAA 1 node3 Activated Pingable cool Active 

的想法是解析第二文件首先由節點值來存儲狀態,索引到陣列hash。然後在第一個文件,對所有指數環如果在f1$3值的散列值相匹配,因此打印狀態,並沒有發現只是打印NA