【问题标题】:Merge files where some columns matched合并某些列匹配的文件
【发布时间】:2019-02-22 08:32:23
【问题描述】:

匹配两个文件中的第 1、2、3 列,如果它们相等。

对于列匹配的文件,将 file1 中第 4 列的值写入 file2 如果没有匹配则写NA

文件1

31431 37150 100 10100
31431 37201 100 12100
31431 37471 100 14100

文件2

31431 37150 100 14100
31431 37131 100 14100
31431 37201 100 14100
31431 37478 100 14100
31431 37471 100 14100

期望的输出:

31431 37150 100 14100 10100
31431 37131 100 14100 NA
31431 37201 100 14100 12100
31431 37478 100 14100 NA
31431 37471 100 14100 14100

我试过了

awk '
FNR==NR{
  a[$1 $2 $3]=$4
  next
}
($1 in a){
  $1=a[$1]
  found=1
}
{
  $0=found==1?$0",":$0",NA"
  sub(/^...../,"&,")
  $1=$1
  found=""
}
1
' FS=" " file1 FS=" " OFS="," file2

【问题讨论】:

  • FS=" " file1 FS=" " OFS="," file2 中设置 FS 时你想做什么?您将 OFS 设置为 , 并在代码中对逗号进行了一些额外的硬编码,但在您的预期输出中没有任何逗号的迹象。为什么?

标签: awk


【解决方案1】:
$ awk '      {k=$1 FS $2 FS $3} 
     NR==FNR {a[k]=$4; next} 
             {$(NF+1)=k in a?a[k]:"NA"}1' file1 file2

31431 37150 100 14100 10100
31431 37131 100 14100 NA
31431 37201 100 14100 12100
31431 37478 100 14100 NA
31431 37471 100 14100 14100

【讨论】:

    【解决方案2】:

    请您尝试关注一下。

    awk 'FNR==NR{a[$1,$2,$3]=$NF;next} {print $0,($1,$2,$3) in a?a[$1,$2,$3]:"NA"}' Input_file1  Input_file2
    

    或者根据 Ed sir 的评论为字段创建一个变量。

    awk '{var=$1 OFS $2 OFS $3} FNR==NR{a[var]=$NF;next} {print $0,var in a?a[var]:"NA"}' Input_file1  Input_file2
    

    输出如下。

    31431 37150 100 14100 10100
    31431 37131 100 14100 NA
    31431 37201 100 14100 12100
    31431 37478 100 14100 NA
    31431 37471 100 14100 14100
    

    说明:现在为上述代码添加说明。

    awk '
    {
      var=$1 OFS $2 OFS $3              ##Creating a variable named var whose value is first, second ansd third field of current lines of Input_file1 and Input_file2.
    }
    FNR==NR{                            ##Checking condition FNR==NR which will be TRUE when first Input_file1 is being read.
      a[var]=$NF                        ##Creating an array named a whose index is variable var and value is $NF of curent line.
      next                              ##next keyword will skip all further lines from here.
    }
    {
      print $0,var in a?a[var]:"NA"     ##Printing current line value and along with that printing either value of a[var] or NA based upon if var present in array a then print a[var] else print NA.
    }'  Input_file1  Input_file2        ##Mentioning Input_file names here.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-09
      • 1970-01-01
      • 2017-07-07
      • 1970-01-01
      • 1970-01-01
      • 2019-10-09
      • 1970-01-01
      相关资源
      最近更新 更多