This is a test version of Biostars. For the public version, visit https://www.biostars.org.
bedtools what in B absent from A

I have two files A.bed

chr1    100 200
chr1    800 900

B.bed

chr1    130 201
chr1    180 220
chr1    600 700

I want to intersect A with B. But also I want in the results what is in B that does not intersect with A

So If I used

bedtools intersect -a A.bed -b B.bed  -r -wao 

chr1    100 200 chr1    130 201 70
chr1    100 200 chr1    180 220 20
chr1    800 900 .   -1  -1  0

but I will miss

chr1    600 700 .   -1  -1  0

which I could get from

bedtools intersect -a B.bed  -b A.bed  -r -wao

chr1    130 201 chr1    100 200 70
chr1    180 220 chr1    100 200 20
chr1    600 700 .   -1  -1  0

I want the end result to be something like:

chr1    100 200 chr1    130 201 70
chr1    100 200 chr1    180 220 20
chr1    800 900 .   -1  -1  0
chr1    600 700 .   -1  -1  0

what I can do is:

bedtools intersect -a A.bed -b B.bed  -r -wao > result.bed
bedtools intersect -a B.bed  -b A.bed  -r -wao | awk '{if($NF == 0){print $0}}' >>  result.bed

But I do not think that this is the right way

Thanks,

sequencing bed software

1 answer

Maybe a bit clunky but:

bedtools intersect -a A.bed -b B.bed -r -wao >out1.bed

bedtools intersect -a B.bed -b A.bed -v >out2.bed

cat out1.bed out2.bed | sort -k1,1 -k2,2n > outfinal.bed

I tried it first but does not give the desired results:

chr1    100 200 chr1    130 201 70
chr1    100 200 chr1    180 220 20
chr1    800 900 .   -1  -1  0
chr1    600 700 .   -1  -1  0

It will give

chr1    100 200 chr1    130 201 70
chr1    100 200 chr1    180 220 20
chr1    800 900 .   -1  -1  0
chr1    600 700

and u can use bedtools sort -i stdin will do the same result as sort -k1,1 -k2,2n

Log in to answer this question.