如何通过具有公共头合并两个文件的行?


8

我想基于两个文件中的公共数据合并它们作为标题。

以下是示例

文件1

>Feature scaffold1
1   100  g
101 200  g
201 300  g
>Feature scaffold2
1   100  g
01  500  g
>Feature scaffold3
10  500  g
>Feature scaffold4
10  300  g

文件2

>Feature scaffold1
500 500 r
900 1000    r
>Feature scaffold2
200 300 r
>Feature scaffold3
100 200 r
>Feature scaffold4
500 600 r
>Feature scaffold5
1   1000    r

这是我想要的输出:

>Feature scaffold1
1   100 g
101 200 g
201 300 g
500 500 r
900 1000    r
>Feature scaffold2
1   100 g
01  500 g
200 300 r
>Feature scaffold3
10  500 g
100 200 r
>Feature scaffold4
10  300 g
500 600 r
>Feature scaffold5
1   1000    r

我已经尝试了一些awk和sed,但是显然没有成功,我该怎么做?

Answers:


7

Awk 解:

awk '/^>/{ k=$1 FS $2 }
     NR==FNR{ 
         if (!/^>/) a[k]=(a[k]!="")? a[k] ORS $0: $0; next
     }
     k in a{ 
         print $0 ORS a[k]; delete a[k]; next 
     }1' file1 file2
  • /^>/{ k=$1 FS $2 }-在遇到标题行(即>Feature ...)时- k从第一字段$1和第二$2字段组成键
  • NR==FNR{ ... }-处理第一个输入文件(file1):
    • if (!/^>/) a[k]=(a[k]!="")? a[k] ORS $0: $0- 使用当前键将非标题行累积到数组中ak
    • next -跳转到下一条记录
  • k in a-如果基于file2记录的当前键在数组中a(基于file1记录):
    • print $0 ORS a[k] -打印相关记录
    • delete a[k] -删除已处理的项目

输出:

>Feature scaffold1
1   100  g
101 200  g
201 300  g
500 500 r
900 1000    r
>Feature scaffold2
1   100  g
01  500  g
200 300 r
>Feature scaffold3
10  500  g
100 200 r
>Feature scaffold4
10  300  g
500 600 r
>Feature scaffold5
1   1000    r

4

另一种方法并使其更简单。

grep -v '^scaffold' <(awk -v RS='>Feature ' \
    'NF{s[$1]=s[$1]$0} END{for (x in s)print RS""s[x]}' file[12])
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.