合并键值上的两个tsv文件,删除没有所有字段的列

时间:2016-06-02 21:57:07

标签: bash shell

我正在尝试在公共密钥上合并两个TSV列。假设文件A是:

a   100
b   200
c   300

和文件B是:

a   "hello"
c   "my name is"

我希望输出文件看起来像:

a   100 "Hello"
c   300 "my name is"

到目前为止,我已经创建了一个如下所示的文件:

a   100 "Hello"
b   200 ""
c   300 "my name is"

我想删除多余的不需要的行,因为它没有所有字段。

这是我到目前为止的代码

 awk '
 NR==1{print "column_A","column_B","column_C"}

 FNR==NR{
          A[$1]=$2
          next 
        }
       {
            print $0,( f=$1 in A ? A[$1] : "" )
            if(f) delete A[$1]
        }
     END{
           for(i in A)
               print i,"",A[i]
        }
' OFS='\t' file2 file1

有没有办法对此代码进行轻微修改以获得该输出?

谢谢!

1 个答案:

答案 0 :(得分:2)

使用join命令:

<table class="table table-bordered background-color: white">
  <thead>
    <tr>
      <th>example table</th>
    </tr>
  </thead>
</table>

请注意,这要求输入文件在加入字段中排序。如果他们不是,您可以使用流程替换。

join -t$'\t' file1 file2