Generating the output file name from the input file in bash script
1
0
Entering edit mode
8.8 years ago
Fluorine ▴ 100

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 • 9.2k views
ADD COMMENT
5
Entering edit mode
8.8 years ago
for file in *.sam; do samtools view -bS $file > ${file/%.sam/.bam}; done
ADD COMMENT
1
Entering edit mode
Learn something new everyday. I always used basename but this is better in so many ways.
ADD REPLY
1
Entering edit mode

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
ADD REPLY
0
Entering edit mode

Thank you! That saved so much time :)

ADD REPLY

Login before adding your answer.

Traffic: 2132 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6