2
$\begingroup$

I have a large BAM file and I want to filter it by just what's defined in a bed file, and write it to a new file.

Is it possible to do this with samtools, and if so, how? Is there a better tool I could use to do this?

$\endgroup$
3
  • 1
    $\begingroup$ Did you look at the options for samtools view? $\endgroup$
    – swbarnes2
    Feb 20, 2020 at 19:22
  • $\begingroup$ ´samtools view` has filtering options for BED files as reference. Type samtools view and check available flags. $\endgroup$
    – user3051
    Feb 20, 2020 at 20:49
  • $\begingroup$ Hi, i.think your question needs more specific details $\endgroup$
    – M__
    Feb 20, 2020 at 22:08

2 Answers 2

5
$\begingroup$

Thanks to the helpful comments I figured it out:

samtools view -b -h -L bedfile.bed originalbam.bam > newbam.bam

-b = Output as bam file
-h = include header
-L = only output alignments overlapping the input BED file

$\endgroup$
2
$\begingroup$

You can also do this with bedtools intersect:

bedtools intersect -abam input.bam -b bedfile.bed > output.bam

This should be identical to the samtools view answer. One further feature though is you can output all reads that don't overlap with the regions in bedfile.bed by adding the -v flag.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.