1) Renaming contigs
If the order isn't changing you can use
samtools reheader (http://www.htslib.org/doc/samtools-reheader.html). This works because BAM files don't actually store the contig names, but the contig indices.
Picard ReplaceSamHeader should do a similar thing.
Caveat: I'm not aware of any tool that correctly updates SAM tags such as the SA when renaming contigs. Your split reads will be broken.
samtools reheader only works if the contigs you are removing are the final contigs. Internally, BAM uses the index (not the name) of the contig each read aligns to. Changing
[chr1, chr1_Un,chr2] to
[1,2] deletes "chr2" and remaps all "chr1_Un" reads to "2". It does not rename "chr2" aligned reads to "2".
2) Delete additional contigs
It's unclear what you want to do with reads that are mapped to contigs to delete. Do you want to:
- Remove them from the file:
samtools view -L to_retain.bed should do the trick.
Note that this will also filter out unmapped reads.
If you want to keep unmapped reads you need to flip it and use
samtools view -L to_remove.bed -U output.bam > /dev/null
You'll need to set the unmapped SAM flag and remove the contig alignment.
Same caveat: I'm not aware of any tool that correctly updates SAM tags such as the SA when renaming contigs. Your split reads will be broken.
TLDR: You're probably better off realigning to the new reference.