如何使用awk基于公共字符串(在不同的列号中)合并文件

时间:2017-03-22 23:02:30

标签: awk merge

文件1:

000001 c-2-3 p045 238744
000001 c-2-4 p042 439709
000002 c-2-4 p055 234744
000003 c-2-5 p099 956755
000004 c-2-9 p064 504435
000005 c-1-5 p043 384029
000006 c-2-2 p011 434444
000009 c-1-3 p083 035905

file2的:

000001 1 0 0 rs333 HESN
000002 1 0 0 rs333 POS
000003 1 0 0 rs333 POS
000004 0 1 0 rs333 POS
000005 0 0 1 rs333 NEG
000008 1 0 0 rs333 POS

以下awk命令:

awk 'NR==FNR {h[$1] = $0; next} {print $1,$2,$3,$4,h[$1]}' file2 file1 > file3

产生以下文件:

file3的:

000001 c-2-3 p045 238744 000001 1 0 0 rs333 HESN
000001 c-2-4 p042 439709 000001 1 0 0 rs333 HESN
000002 c-2-4 p055 234744 000002 1 0 0 rs333 POS
000003 c-2-5 p099 956755 000003 1 0 0 rs333 POS
000004 c-2-9 p064 504435 000004 0 1 0 rs333 POS
000005 c-1-5 p043 384029 000005 0 0 1 rs333 NEG
000006 c-2-2 p011 434444
000009 c-1-3 p083 035905

但是,file1实际上是这样的:

file1b:

c-2-3 p045 238744 000001
c-2-4 p042 439709 000001
c-2-4 p055 234744 000002
c-2-5 p099 956755 000003
c-2-9 p064 504435 000004
c-1-5 p043 384029 000005
c-2-2 p011 434444 000006
c-1-3 p083 035905 000009

如何更改awk命令以接受file1b(而不是file1)并获取相同的输出(file3)。另外,我如何排除file3中的冗余信息(即第5列)?

使用file1b和file2的所需输出:

000001 c-2-3 p045 238744 1 0 0 rs333 HESN
000001 c-2-4 p042 439709 1 0 0 rs333 HESN
000002 c-2-4 p055 234744 1 0 0 rs333 POS
000003 c-2-5 p099 956755 1 0 0 rs333 POS
000004 c-2-9 p064 504435 0 1 0 rs333 POS
000005 c-1-5 p043 384029 0 0 1 rs333 NEG
000006 c-2-2 p011 434444
000009 c-1-3 p083 035905

谢谢!

1 个答案:

答案 0 :(得分:2)

awk救援!

awk 'NR==FNR {k=$1; $1=""; a[k]=$0; next} 
             {k=$NF; NF--; print k,$0 a[k]}' file2 file1b 

000001 c-2-3 p045 238744 1 0 0 rs333 HESN
000001 c-2-4 p042 439709 1 0 0 rs333 HESN
000002 c-2-4 p055 234744 1 0 0 rs333 POS
000003 c-2-5 p099 956755 1 0 0 rs333 POS
000004 c-2-9 p064 504435 0 1 0 rs333 POS
000005 c-1-5 p043 384029 0 0 1 rs333 NEG
000006 c-2-2 p011 434444
000009 c-1-3 p083 035905

有一些微妙的技巧用于简化代码...