This is a test version of Biostars. For the public version, visit https://www.biostars.org.
How to remove from BAM file header all chromosomes, except chrM

This is the header of my BAM file:

@HD VN:1.4  SO:coordinate
@SQ SN:chr1 LN:248956422
@SQ SN:chr2 LN:242193529
@SQ SN:chr3 LN:198295559
@SQ SN:chr4 LN:190214555
@SQ SN:chr5 LN:181538259
@SQ SN:chr6 LN:170805979
@SQ SN:chr7 LN:159345973
@SQ SN:chr8 LN:145138636
@SQ SN:chr9 LN:138394717
@SQ SN:chr10    LN:133797422
@SQ SN:chr11    LN:135086622
@SQ SN:chr12    LN:133275309
@SQ SN:chr13    LN:114364328
@SQ SN:chr14    LN:107043718
@SQ SN:chr15    LN:101991189
@SQ SN:chr16    LN:90338345
@SQ SN:chr17    LN:83257441
@SQ SN:chr18    LN:80373285
@SQ SN:chr19    LN:58617616
@SQ SN:chr20    LN:64444167
@SQ SN:chr21    LN:46709983
@SQ SN:chr22    LN:50818468
@SQ SN:chrX LN:156040895
@SQ SN:chrY LN:57227415
@SQ SN:chrM LN:16569
@SQ SN:chr1_KI270706v1_random   LN:175055
@SQ SN:chr1_KI270709v1_random   LN:66860
@SQ SN:chrUn_KI270383v1 LN:1750
@SQ SN:chrUn_KI270393v1 LN:1308
@SQ SN:chr2_KI270752v1  LN:27745

Is this possible to remove all chr1-22, X,Y,chrUn and leave only @SQ SN:chrM LN:16569?

This is my try, but it is removing all since bam files is now empty.

samtools view -H test.bam | sed '/chrEBV/d;/random/d;/chrUn/d;/chr[0-9]/d;/chr[1-2][0-9]/d;chr[X]/d;chr[Y]/d' > test.new.bam
samtools

1 answer

samtools view -H test.bam | awk '/^@SQ/ {if($2!="SN:chrM") next;} {print;}'

Log in to answer this question.