This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Find and replace the RNAME field in BAM/SAM file

Hello everyone,

I wish to change the name of the contigs in a SAM file.
For this, I have to change each line of the RNAME field in the SAM file, based on a reference list.txt file with the format:

head -2 list.txt
>former_contig_name_1     new_contig_name_1
>former_contig_name_2     new_contig_name_2

I have tried different command to replace the former_name by the new_name, but it is a bit tricky.
The AWK command is printing the entire BAM file for one substitution, and I have failed to make a loop with it.
The SED command seems not to consider different fields, and I don't know how to target the RNAME field (3rd field).

cat list.txt | while read f ;  
do
    echo $f > temp_file ;
    former_name=$(cut -f1 temp_file) ;
    new_name=$(cut -f2 temp_file) ;
    sed -i  's/$former_name/$new_name/g' file.sam  ;
done 

Would anyone know a more simple way to do it? Or just know how to target the 3rd column of the file.sam with sed? Thanks for the help!

samtools bam loop sed sam

1 answer

See: Bam File: Change Chromosome Notation
Bam Header Edit

Log in to answer this question.