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?
Bioinformatics Stack Exchange is a question and answer site for researchers, developers, students, teachers, and end users interested in bioinformatics. It only takes a minute to sign up.
Sign up to join this communityThanks 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
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.
samtools view
and check available flags. $\endgroup$