【问题标题】:Awk - Match Values Between Two Filesawk - 两个文件之间的匹配值
【发布时间】:2020-12-28 06:09:51
【问题描述】:

我有两个要比较的文件,并使用这两个文件中存在的数据创建一个 final.txt 文件。

File1 - 第 1 列和 File2 - 第 2 列包含我需要在两个文件之间匹配的值。

所以本质上,我试图 -> 从 File1 中获取 column1,如果 file2 的 column2 中有匹配项,则将 File1Column1、File1Column2 和 File2Column1 写入一个名为 final.txt 的新文件。

示例

文件 1

1000,Brian
1010,Jason
400,Nick

文件 2

3044 "1000"
4466 "400"
1206 "1010"

输出文件的样子

1000,Brian,3044
1010,Jason,1206
400,Nick,4466

我的测试代码没有显示任何结果

awk -F"[,]" 'NR==FNR{a[$1]=$1","$2;next} ($2 in a){print a[$2]","$1}' file1.txt file2.txt

我相信我应该能够用 awk 做到这一点,但由于某种原因,我真的在努力解决这个问题。任何帮助将不胜感激。

谢谢

【问题讨论】:

  • 请不要以使答案无效的方式编辑问题。您之前已经接受了一个答案。不接受答案,然后更改/添加问题是对及时帮助您的用户的不尊重。请不要这样做。
  • 谢谢你。另一个注意事项:添加的重复链接可以作为参考,但它不是重复的。

标签: linux shell awk


【解决方案1】:

您能否尝试在 GNU awk 中使用您展示的示例进行跟踪、编写和测试。

awk '
FNR==NR{
  gsub(/"/,"",$2)
  arr[$2]=$1
  next
}
FNR==1{
  FS=","
  OFS=","
  $0=$0
}
($1 in arr){
  print $0,arr[$1]
}
'  Input_file2  Input_file1

说明:为上述添加详细说明。

awk '                ##Starting awk program from here.
FNR==NR{             ##Checking condition FNR==NR which will be TRUE when Input_file1 is being read.
  gsub(/"/,"",$2)    ##globally substituting " in 2nd field with NULL.
  arr[$2]=$1         ##Creating array arr with index of 2nd field and value of 1st field.
  next               ##next will skip all further statements from here.
}
FNR==1{              ##Checking condition if this is first line of Input_file1.
  FS=","             ##Setting FS as comma here.
  OFS=","            ##Setting OFS as comma here.
  $0=$0              ##Reassigning current line to itself so that field separator values will be implemented to current line.
}
($1 in arr){         ##Checking condition if 1st field is present in arr then do following.
  print $0,arr[$1]   ##Printing current line and value of array arr.
}
' file2 file1        ##Mentioning Input_file names here.

【讨论】:

    【解决方案2】:

    您没有在示例输入/输出中的两个输入文件之间包含任何不匹配的行,因此对于这些情况,这可能会或可能不会做您想要的:

    $ cat tst.awk
    BEGIN { FS="[[:space:]\",]+"; OFS="," }
    NR==FNR {
        map[$2] = $1
        next
    }
    { print $0, map[$1] }
    

    $ awk -f tst.awk file2 file1
    1000,Brian,3044
    1010,Jason,1206
    400,Nick,4466
    

    【讨论】:

      猜你喜欢
      • 2016-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-09
      • 2015-08-10
      • 2018-07-12
      相关资源
      最近更新 更多