首页 > 解决方案 > 在 awk 中使用数组来匹配行

问题描述

我正在尝试使用awk匹配两个文件(file1 和 file2)。对于 file2 中与 file1 匹配的列的每一行,我希望命令打印出 file1 中的第二列。

我在这里查看了几个解决方案,并找到了一些可行的方法(部分),但我不明白它是如何工作的。

awk 'NR==FNR {a[$1]=$2; next} $1 in a{print a[$1]}' file1 file2 >> output

这是输入的示例:

#File1
0_1   apple
0_2   mango
0_3   banana
...
3_1   durian
3_4   dragonfruit
3_20  pear
#File2
0_1   3_1
0_1   3_1
0_2   3_4
0_3   3_20

当我将 File2 的第一列与 File1 匹配时,上面的 awk 命令会返回我想要的结果。

#Output
apple
apple
mango
banana

所以很自然地,我稍微调整了该行以对 File2 中的第二列执行相同的操作。

awk 'NR==FNR {a[$1]=$2; next} $2 in a{print a[$1]}' file1 file2 >> output

但是当我期望时,我收到与上面完全相同的结果:

#Expected output
durian
durian
dragonfruit
pear

更糟糕的是,当我这样做时,我得到了所需的输出:

awk 'NR==FNR {a[$1]=$2; next} $1 in a{print a[$2]}' file1 file2 >> output

有人可以向我解释这背后的逻辑(为数组赋值)还是在其他地方出了问题?

标签: awktext-processing

解决方案


您能否通过以下说明您使用的代码。它可以帮助你理解数组的概念。

awk '                      ##Starting awk program from here.
NR==FNR{                   ##Checking condition FNR==NR which will be TRUE once first Input_file named file1 is being read.
  a[$1]=$2                 ##Creating an array named a whose index is $1 of current line and value is $2(2nd field) of current line.
  next                     ##next will skip all further statements from here.
}                          ##Closing BLOCK for FNR==NR condition here.
$2 in a{                   ##Checking condition(which will be executed only when 2nd Input_file named file2 is being read.
  print a[$1]              ##Now printing value of array a whose index is $1 of current line.
}                          ##Closing BLOCK for $2  in a condition here.
' file1 file2 >> output    ##Mentioning Input_file names and placing output into output file here.

关于 Array 概念的补充说明:

  • 做什么a[$1]=$2?:这意味着我们正在创建一个名为 a 的数组,其索引(通过它识别任何项目),其值为 $2(当前行的第二个字段)。
  • 示例a[$1]=$2让我们以0_1 apple第一个 Input_file 中的示例为例,其中数组将存储为a[0_1]=apple,如上所述,它的索引是 0_1,值是苹果。
  • $2 in a条件做什么?:这个语句实际上是一个条件,它检查当前行的 $2 是否进入数组 a (当然,它检查数组 a 的所有索引并将此字符串与它们进行比较,如果它们匹配或不匹配)是否匹配找到然后打印数组 a 的值,其值为a[$1]

推荐阅读