Subset smaller BAM to contain several thousand rows from multiple chromosomes There are many cases whereby I would like to subset a BAM to create a small file in order to work with (e.g. algorithmic testing, debugging, etc.)

Normally I do the following, which will subset the BAM file.bam and keep the header

samtools view -H file.bam &gt; header.sam
samtools view file.bam | head -n 5000 | cat header.sam - | samtools view -Sb - &gt; file.unique.bam


In this case, I would like 5000 rows in chromosome 1 and 5000 in chromosome 2. 

I could first try grepping by individual chromosome, and then combining the two SAMs

e.g. here's complete BAM with grepped chr1 and (incorrect but complete) header

samtools view -H file.bam &gt; header.sam
samtools view file.bam | grep "chr1" | cat header.sam - | samtools view -Sb - &gt; file.unique.bam


but then I have two problems: 

(1) I may not be grepping the alignments to chromsome 2---there may exist BAM rows which contain 'chr2' but are not alignments. 

(2) I think one must manually edit the header. There's probably no way around this. 

Is there an easy way, Bioinformatics SO?
If you're not too hung up on exact numbers like 5000 reads then you can do that with a single samtools command:

samtools view -bo subset.bam -s 123.4 alignments.bam chr1 chr2


That will select 40% (the .4 part) of the reads (123 is a seed, which is convenient for reproducibility). The convenient part of this is that it'll keep mates paired if you have paired-end reads. For 5000 reads per chromosome just change the .4 part to a sufficiently small number.

In general you don't really need to subset the header. Some tools will perform a bit better if you do, but you'll generally get the same results regardless.