How to subset a BAM by a list of QNAMEs? I have a text file 'qnames.txt' with QNAMEs in the following format:
EXAMPLE:QNAME1
EXAMPLE:QNAME2
EXAMPLE:QNAME3
EXAMPLE:QNAME4
EXAMPLE:QNAME5

I would like to subset my BAM file.bam via all of these QNAMEs into a new SAM.
Naturally, I can do this individually, e.g.
samtools view file.bam | grep 'EXAMPLE:QNAME1' &gt; subset.bam

But I'm unsure how to do this for a list of QNAMES:

How do I write a for loop that will do all of these queries, outputting the correct SAM needed?
I could write a for loop that creates n SAM files, and then cats them…

Is there a way to specifically grep by QNAME? The above may grep reads that may not be associated with the correct QNAME?

How do I keep the BAM header?
use picard FilterSamReads http://broadinstitute.github.io/picard/command-line-overview.html#FilterSamReads


  READ_LIST_FILE (File) Read List File containing reads that will be included or excluded from the OUTPUT SAM or BAM file. Default value: null.