2017-04-20 12 views
1

次の2つのファイルがあります。3つの列の値に基づいてそれらを結合する必要があります。3つの列に基づいて2つのファイルを結合します

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 - 最初の組み合わせを使用して、第2のファイルf2における5番目のフィールド$5の値を格納します$1とt HIRDは

$7="NA";キー配列として$3フィールド -

「NA」のデフォルト値で追加の7番目のフィールド $7を開始します
1

を、以下のようにのような出力を生成し

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 

Awkロジックを使用しますあなたが必要でした。

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

アイデアは、解析アレイhashにノード値によってステータス、インデックスを格納する第二のファイルです。最初のファイルでは、のインデックスがすべてのループになり、$3の値がf1の値とハッシュ値が一致する場合は、それに応じてステータスが出力され、見つからない場合はNAと印刷されます。

関連する問題