This is a test version of Biostars. For the public version, visit https://www.biostars.org.
samtools/sed for editing bam file

I have the following sed command that change the chromosome name:

for file in /myoldpath/*.bam
do
filename=echo $file | cut -d "." -f 1
samtools view -H $file | sed -e 's/SN:([0-9XY])/SN:chr\1/' -e 's/SN:MT/SN:chrM/' | samtools reheader - $file > /mynewpath/${filename}_chr.bam
done

My quesion is how to insert the result in a new path while keeping the variable $filename as part of every new file name? it always insert the result in /myoldpath/ or literally "filename.chr.bam" in the /mynewpath/ am i missing something in the syntax of that part "$file > /mynewpath/${filename}_chr.bam"?

thank you in advance

sed samtools

Please use ADD REPLY/ADD COMMENT when responding to existing posts to keep threads logically organized.

Please accept (use the check mark against the answer) if the solution works for you to provide closure to the thread.

1 answer

This should work.

for file in /myoldpath/*.bam
do
filename=`echo $file | awk -F"/" '{ print $NF}' | cut -d "." -f1 `
samtools view -H /myoldpath/$file | sed -e 's/SN:([0-9XY])/SN:chr\1/' -e 's/SN:MT/SN:chrM/' | samtools reheader - /myoldpath/$file > /mynewpath/${filename}_chr.bam
done

Its better to say:

filename=` echo $file | awk -F"/" '{ gsub(".bam" ,"", $NF); print $NF}' `

P.S There are many ways todo this, but I just want to modify your command, so that you understand it easily.

Log in to answer this question.