【问题标题】:Using arrays in awk to match lines在 awk 中使用数组来匹配行
【发布时间】:2019-08-18 04:14:23
【问题描述】:

我正在尝试使用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

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

【问题讨论】:

    标签: awk text-processing


    【解决方案1】:

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

    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 的示例: 让我们以第一个 Input_file 中的 0_1 apple 为例,其中数组将存储为 a[0_1]=apple,如上所述,它的索引是 0_1 和值是苹果。
    • $2 in a 条件是做什么的?: 这个语句实际上是一个条件,它检查当前行的 $2 是否进入数组 a(当然它检查数组的所有索引a 并将此字符串与它们进行比较,如果它们匹配或不匹配)如果找到任何匹配项,则打印值为 a[$1] 的数组 a 的值

    【讨论】:

    • 您好 RavinderSingh13,感谢您的详细回答;下次当我尝试理解 awk 命令时,我肯定会分解它们。我想再澄清一个问题:当没有分配a[$2] 时,print a[$2] 是什么意思?它似乎不会直接引用之前分配给数组的值,我对它从 $1 in a$2 in a 命令给出的不同输出集感到​​非常困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 2018-08-17
    相关资源
    最近更新 更多