bash - 使用两列比较三个文件并使用 awk/sed 在每个文件中打印唯一条目

标签 bash awk sed overlap

<分区>

我有以下格式的三个文件:

$ cat a.bed 
chr1    6   6   aa
chr1    8   8   bb
chr2    22  22  aa
chr3    24  24  bb

$ cat b.bed 
chr1    12  12  cc
chr1    6   6   dd
chr5    14  14  cc

$ cat c.bed 
chr1    8   8   ss
chr4    11  11  dd
chr1    6   6   aa

我想使用前两列比较这些文件,并为每一行打印信息,无论它存在于一个文件还是多个文件中,例如:

chr1    6   6   aa  3   a.bed,b.bed,c.bed
chr1    8   8   bb  2   a.bed,c.bed
chr2    22  22  aa  1   a.bed
chr3    24  24  bb  1   a.bed
chr1    12  12  cc  1   b.bed
chr5    14  14  cc  1   b.bed
chr4    11  11  dd  1   c.bed

第 5 列给出了它所在的文件数,第 6 列给出了文件名。

最佳答案

awk 助您一臂之力!

$ awk '{a[$1,$2]=(($1,$2) in a?a[$1,$2]",":$0 OFS)FILENAME}
   END{for(k in a) print a[k]}' {a,b,c}.bed

虽然结果不会按相同的顺序排列。

解释

x=c?a:b is the ternary operator, sets x to a or b based on value of c (similar to if-then-else). Here we assign the value of map for key ($1,$2) either by appending FILENAME (if already exists) or setting to the current line (again by appending FILENAME). In the END block, just iterates over this map, and prints the values.

关于bash - 使用两列比较三个文件并使用 awk/sed 在每个文件中打印唯一条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48875411/

相关文章:

bash - 在 CentOS 6 中添加/更新/查找 .bashrc 或 .bash_profile 以使 Laravel 新命令正常工作

Linux - 如何根据字段值从文件中删除某些行

bash - 在 awk printf 中使用可变长度的提示

python - 操作系统调用给予权限被拒绝

bash :如果 [ "echo test"== "test"];然后回显 "echo test outputs test on shell"fi;可能的?

linux - 如何获取第二个字符串并对其执行操作?

perl - 根据当前文件的内容从 awk 搜索/读取另一个文件,是否可能?

linux - 我如何 grep 出相同模式的多行?

unix - sed -i 选项在 solaris 上不起作用

xml - 使用sed从XML文件中删除节点和数据