This is a test version of Biostars. For the public version, visit https://www.biostars.org.
bedtools intersect with match on name column

I have files a.bed and b.bed

a.bed

chr1 10 20 geneA
chr1 30 40 geneB

b.bed

chr1 5 15 geneA
chr1 10 25 geneB

if I intersectbed those files I will obtain:

chr1 10 15 geneA
chr1 10 20 geneA

But I would like the name column to match between files so that i will obtain:

chr1 10 15 geneA

If name column does not match, I don't want to output the intersection. I can't find any option in intersectbed to "force identical name", any suggestions?

bedtools intersectbed

2 answers

I would do a two-step process:

## First use the -wa -wb options to report both the entire entry of -a and of -b in case of overlap,
## and then use awk to check if the genes are the same.
## If so, keep the row, if not discard:

bedtools intersect -a a.txt -b b.txt -wa -wb | awk 'OFS="\t" {if ($4 == $8) print}' > intermediate.txt

## Then use intersect again to get the actual overlap:
bedtools intersect -a <(cut -f1-4 intermediate.txt) -b <(cut -f 5-8 intermediate.txt)

Sorry, it is not working, here is the problem:

In the second step, you don't intersect line by line, so the problem is still the same. Just try it and you will see.

Based on the data you provided it gives exactly the result you intended:

enter image description here

My bad, my example was not a MWE, I will validate your answer. If you replace 10 25 by 10 35 here you will see the problem.

I finaly found out how to do it:

As I want a Chromosome and name match, I just make a bedfile in the format chr+name start end name, and it works well.

Log in to answer this question.