Question: Generating the output file name from the input file in bash script
0
gravatar for Grinch
3.7 years ago by
Grinch30
Germany
Grinch30 wrote:

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 • 5.2k views
ADD COMMENTlink modified 3.7 years ago by Jorge Amigo11k • written 3.7 years ago by Grinch30
5
gravatar for Jorge Amigo
3.7 years ago by
Jorge Amigo11k
Santiago de Compostela, Spain
Jorge Amigo11k wrote:
for file in *.sam; do samtools view -bS $file > ${file/%.sam/.bam}; done
ADD COMMENTlink modified 3.7 years ago • written 3.7 years ago by Jorge Amigo11k
1
Learn something new everyday. I always used basename but this is better in so many ways.
ADD REPLYlink written 3.7 years ago by 5heikki8.3k
1

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 REPLYlink written 3.7 years ago by Jorge Amigo11k

Thank you! That saved so much time :)

ADD REPLYlink written 3.7 years ago by Grinch30
Please log in to add an answer.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 1132 users visited in the last hour