<p>It sounds like <code>bedtools intersect</code> will work for you:</p>

<pre><code>bedtools intersect -wa -a &lt;alignment.bam&gt; -b &lt;region.bed&gt; &gt; &lt;intersect_alignment.bam&gt;
</code></pre>

<blockquote>
  <p>When a BAM file is used for the A file, the alignment is retained if overlaps exist, and exlcuded if an overlap cannot be found.  If multiple overlaps exist, they are not reported, as we are only testing for one or more overlaps.</p>
</blockquote>

<p>It's easy enough to wrap this up into a <code>for</code> loop for batch processing (line breaks can be removed if desired):</p>

<pre><code> for alnBam in alignmentFiles*.bam;
   do echo ${alnBam};
   bedtools intersect -wa -a ${alnBam} -b &lt;region.bed&gt; &gt; intersect_${alnBam};
 done
</code></pre>

<p>There are a lot of other options which should cover most related uses. For more details, just run "bedtools intersect" (with no arguments).</p>

CC BY-SA 3.0
2017-06-04T11:29:12.203Z
In your example shell code, `${x}` should be `${alnBam}`.
Matt Bashton
CC BY-SA 3.0
2017-06-04T01:31:45.110Z
2017-06-04T11:30:33.870Z
2017-06-04T11:30:33.870Z
gringer
<p>I was given a list of target regions in BED and many exome alignments in BAM. I was asked to extract on-target alignments from these BAMs to save disk space. I know I can use bedtools to extract sub-BAMs. I am thinking to write a script to apply bedtools to all BAMs at my hand, but I speculate there may be some more convenient command lines to achieve my goal. How would you do? Thanks.</p>

<sam><linux><bedtools>
How to extract exome on-target reads in batch?
# How to extract exome on-target reads in batch?

(Asked by: username_0 on 2017-06-03)

I was given a list of target regions in BED and many exome alignments in BAM. I was asked to extract on-target alignments from these BAMs to save disk space. I know I can use bedtools to extract sub-BAMs. I am thinking to write a script to apply bedtools to all BAMs at my hand, but I speculate there may be some more convenient command lines to achieve my goal. How would you do? Thanks.

**Tags:** sam, linux, bedtools

---

## 1 answers

### Answer by username_1 on 2017-06-04. Score: 2

It sounds like bedtools intersect will work for you:
bedtools intersect -wa -a  -b  > 


When a BAM file is used for the A file, the alignment is retained if overlaps exist, and exlcuded if an overlap cannot be found.  If multiple overlaps exist, they are not reported, as we are only testing for one or more overlaps.

It's easy enough to wrap this up into a for loop for batch processing (line breaks can be removed if desired):
 for alnBam in alignmentFiles*.bam;
   do echo ${alnBam};
   bedtools intersect -wa -a ${alnBam} -b  > intersect_${alnBam};
 done

There are a lot of other options which should cover most related uses. For more details, just run "bedtools intersect" (with no arguments).

> **Comments:**
> **username_2**: In your example shell code, `${x}` should be `${alnBam}`.  

---

