<p>I want to create two random subsamples from a BAM file. I don&#39;t want to just do &quot;samtools view -s 0.5&quot; twice because I want to put half of the reads into one file and half in the other, without replacement. Is there an easy way to do this? I&#39;ve considered using samtools to output the alignments in SAM format and pipe to the shuf and split commands, I think I&#39;d need to do some extra things to keep the paired-end reads together. Anyone have any ideas?</p>

Assuming single-end reads, something like this should work:

    samtools view -H foo.bam > f1.sam
    cp f1.sam f2.sam
    samtools view foo.bam | awk '{if(NR%2){print >> "f1.sam"} else {print >> "f2.sam"}}'

I'm sure there's a one line version of that, but this is simple enough.

For paired-end reads, just change `NR%2` to `NR%4<2`. Again, there's likely a bug in there, but it's something to start with.
