我有以下两个文件,我需要根据三列的值加入它们,如果不匹配,则在不匹配的列中打印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发布于 2017-04-20 07:55:18
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 Activea[$1,$3]=$5 -将第五个字段$5的值存储在第二个文件f2中,使用第一个$1和第三个$3字段的组合作为数组键。
$7="NA"; -启动另一个具有默认值"NA“的第七个字段$7。
发布于 2017-04-20 07:48:06
使用下面的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中。然后,在第一个文件上,对所有索引进行循环,如果$3中的f1值与散列值匹配,则相应地打印状态,而不是只打印NA。
https://stackoverflow.com/questions/43512905
复制相似问题