# How to extract exome on-target reads in batch?

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.

It sounds like bedtools intersect will work for you:
bedtools intersect -wa -a <alignment.bam> -b <region.bed> > <intersect_alignment.bam>

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 <region.bed> > 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). • In your example shell code, ${x} should be \${alnBam}. Jun 4 '17 at 11:29