This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Generating the output file name from the input file in bash script

I'm writing a shell script that would convert all my .sam files to .bam files. I'm using a loop for all files in the folder that end with .sam. Now my question is how do I write in the script that the output files will have the same name as the input files, but end with .bam?

shell script

1 answer

for file in *.sam; do samtools view -bS $file > ${file/%.sam/.bam}; done
Learn something new everyday. I always used basename but this is better in so many ways.

Thank you! That saved so much time :)

strictly speaking, if you want to make sure that there's no other ".sam" string in the filename that could avoid this code to replace the extension, you can always force the string replacement to start from back:

for file in *.sam; do samtools view -bS $file > ${file/%.sam/.bam}; done

rather than simply

for file in *.sam; do samtools view -bS $file > ${file/.sam/.bam}; done

Log in to answer this question.