如何修复与两个文件之间的字段匹配的代码,并从每个文件输出各种字段? (AWK)

时间:2015-07-09 18:24:09

标签: bash awk

以前很多人回答过,但我在这里挣扎......

代码:

awk '{OFS="\t"}NR==FNR{a[$1]=$1;a[$2]=$3;a[$3]=$4;next} $1 in a{print a[$1],a[$2],a[$3],$1,$3}' file1 file2 > output.txt

文件1:

spot dog black male

felix cat white male

文件2:

spot dog good tall

felix cat bad small

所需的输出:

spot black male spot good

felix white male felix bad

实际输出:

spot black spot good

felix white felix bad

a[$3]未正在打印,或未正确分配...

1 个答案:

答案 0 :(得分:2)

你想要更像这样的东西

awk 'NR==FNR {
    # Don't need a value just presence in the array for the '$1 in a' check.
    a[$1]=""
    # The value of $3 may not be unique so that can't be a key but '$1,3' will be since $1 is unique.
    a[$1,3]=$3
    # Same here as for $3 above.
    a[$1,4]=$4
    next
}
$1 in a {
    print $1, a[$1,3], a[$1,4], $1, $3
}' file1 file2

这里的关键是你只能使用$1作为你的独特(和独特的)键,你必须将它用于所有相关领域。