通过公共字符串组合来自不同文件的两列

时间:2021-03-25 09:26:25

标签: unix awk sed echo

我有两个制表符分隔的文件。

file-1

<头>
NODE_1_length_59711_cov_84.026979_g0_i0_1 K02377
NODE_1_length_59711_cov_84.026979_g0_i0_2
NODE_2_length_39753_cov_84.026979_g0_i0_1 K02377
NODE_2_length_49771_cov_84.026979_g0_i0_2 K16554

................................................ ......................总共 391443 行

file2

<头>
NODE_1_length_59711_cov_84.026979_g0_i0_1 56.54
NODE_1_length_59711_cov_84.026979_g0_i0_2 51.0
NODE_2_length_39753_cov_84.026979_g0_i0_1 12.6
NODE_2_length_49771_cov_84.026979_g0_i0_2 18.9

................................................ ......................总共 391249 行

我想合并这两个文件,保持第一列不变。

<头>
NODE_1_length_59711_cov_84.026979_g0_i0_1 K02377 56.54
NODE_1_length_59711_cov_84.026979_g0_i0_2 51.0
NODE_2_length_39753_cov_84.026979_g0_i0_1 K02377 12.6
NODE_2_length_49771_cov_84.026979_g0_i0_2 K16554 18.9

问题是第一个文件有将近 190 行,我不能直接将它们组合起来,因为它会给出错误的输出。有什么办法可以通过第一列中的公共字符串组合这些文件吗?

2 个答案:

答案 0 :(得分:0)

这可能对您有用(GNU 加入):

join -t$'\t' file1 file2

注意某些 shell 可能不接受 $'\t' 在这种情况下使用文字制表符,这可以通过终端 cntrl-v 制表符键序列输入。

答案 1 :(得分:0)

使用 GNU awk:

awk 'NR==FNR { map[$1]=$2;next } { map1[$1]=$2 } END { PROCINFO["sorted_in"]="@ind_str_asc";for (i in map) { print i"\t"map[i]"\t"map1[i] } }' file-1 file2

说明:

awk 'NR==FNR { 
               map[$1]=$2;                                  # Process the first file only and set up an array called map with the first space separated field as the index and the second the value
               next 
             } 
             { 
               map1[$1]=$2                                  # When processing the second file, set up an second array called map1 and use the first field as the index and the second the value.
             } 
         END { 
               PROCINFO["sorted_in"]="@ind_str_asc";         # Set the index ordering
               for (i in map) { 
                 print i"\t"map[i]"\t"map1[i]                # Loop through the map array and print the values along with the values in map1.
               } 
              }' file-1 file2