【问题标题】:Awk to get file1 column and check column1 of file2,if matches then print the corresponding valueawk 获取 file1 列并检查 file2 的 column1,如果匹配则打印相应的值
【发布时间】:2020-10-29 05:28:39
【问题描述】:

我正在尝试将 file1 的第一列与 file2 的第一列进行比较。如果有匹配-> 打印 file2 的 column2 中的对应值

检查了一些建议,但没有找到正确的代码。

file1 (single column)
987
675
21
23
21
2645

file2 (two columns)
234 def
987 one
22  abc
21  two
675 three
24  rty
25  qwe

预期输出:

one
three
two
two

我正在使用:

awk 'FNR==NR { r[$1] = $0; next; } r[$1] { print r[$1]; next }' file2 file1

我明白了:

987 one
675 three
21  two
21  two

有什么建议吗? 谢谢!

【问题讨论】:

    标签: bash awk


    【解决方案1】:

    这应该可以...

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

    基本上,如果您不想打印第一个字段,只需将第二个字段存储在您的 r 数组中即可。

    第二个next 是多余的;还要使用in 检查数组中的字段是否存在,因为值可能为零(或空字符串),在这种情况下r[$1] 将为假。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-02
      • 2017-07-10
      • 1970-01-01
      • 2013-03-04
      • 1970-01-01
      • 1970-01-01
      • 2018-11-08
      • 1970-01-01
      相关资源
      最近更新 更多