awkでヘッダーを使用して2つのファイルのデータをマージする方法

awkでヘッダーを使用して2つのファイルのデータをマージする方法

2つのファイルがありますA.tsvB.tsv

A.tsv (フィールド区切り記号 = \t):

Sample ID   Internal Control    Result  Consensus   
4686427 Pass    Not Detected    Not Available
4666275 Pass    Detected    Not Available
4666295 Pass    Detected    Available
4644444 Pass    Detected    Available

B.tsv (フィールド区切り記号 = \t):

seqName clade   substitutions   deletions
4666295 A8A yes no
4666275 18A no  yes
4686427 161 no  yes

これら2つのファイルを次のように新しいファイルにマージしたいと思います。

Sample ID   Internal Control    Result  Consensus   clade   substitutions   deletions   
4686427 Pass    Not Detected    Not Available   161 no  yes
4666275 Pass    Detected    Not Available   18A no  yes
4666295 Pass    Detected    Available   A8A yes no
4644444 Pass    Detected    Available

これを作成しましたが、ヘッダーまたは2番目のファイルの最初の行は印刷されません。

awk -F '\t' -v OFS="\t" 'NR==FNR{a[$1]=$0;next}{print $0,a[$1]}' B.tsv A.tsv > C.tsv

それでは、正しく行う方法は何ですか?ありがとう

PS:ファイルをサブサンプリングしましたが、実際のファイルは行と列の面で大きくなります。

ベストアンサー1

努力する:

awk 'BEGIN        { FS=OFS="\t" }
     NR==FNR      { seq=$1; sub(/[^\t]*\t/,""); if(NR==1)hdr=$0; hold[seq]=$0; next }
     FNR==1       { print $0, hdr; next }
     ($1 in hold) { print $0, hold[$1]; next }
                  { print }' fileB fileA >fileC

おすすめ記事