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 > header.sam
samtools view file.bam | head -n 5000 | cat header.sam - | samtools view -Sb - > 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 > header.sam
samtools view file.bam | grep "chr1" | cat header.sam - | samtools view -Sb - > 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?