<p>You can also do this with <a href="https://bedtools.readthedocs.io/en/latest/content/tools/intersect.html" rel="nofollow noreferrer"><code>bedtools intersect</code></a>:</p>
<pre class="lang-sh prettyprint-override"><code>bedtools intersect -abam input.bam -b bedfile.bed &gt; output.bam
</code></pre>
<p>This should be identical to the <code>samtools view</code> answer. One further feature though is you can output all reads that <strong>don't</strong> overlap with the regions in <code>bedfile.bed</code> by adding the <code>-v</code> flag.</p>

CC BY-SA 4.0
2023-05-23T08:32:04.360Z
2023-05-23T08:32:04.360Z
bricoletc
<p>Thanks to the helpful comments I figured it out:</p>
<pre><code>samtools view -b -h -L bedfile.bed originalbam.bam &gt; newbam.bam
</code></pre>
<p>-b = Output as bam file<br />
-h = include header<br />
-L = only output alignments overlapping the input BED file</p>

CC BY-SA 4.0
2020-02-20T21:06:20.237Z
2023-05-09T02:53:27.677Z
2023-05-09T02:53:27.677Z
Kyle
<p>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.</p>

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

CC BY-SA 4.0
2020-02-20T19:22:55.520Z
Did you look at the options for samtools view?
swbarnes2
CC BY-SA 4.0
2020-02-20T22:08:57.877Z
Hi, i.think your question needs more specific details
M__
<sam><samtools><pysam>
How to filter a SAM file by a bed file?
# How to filter a SAM file by a bed file?

(Asked by: username_0 on 2020-02-20)

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?

**Tags:** sam, samtools, pysam
> **Comments:**
> **username_1**: Did you look at the options for samtools view?  
> **username_2**: Hi, i.think your question needs more specific details  

---

## 2 answers

### Answer by username_0 on 2020-02-20. Score: 6 | Accepted answer

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


---

### Answer by username_3 on 2023-05-23. Score: 2

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.


---

