How to change dot to underline in multiple file-names

filenamesrename

I have over 100 files named like

x.assembled.forward.fastq.gz
x(n).unassembled.reverse.fastq.gz

the problem is that the pipelines that I am working with do not accept 'dots' in the file name and I have to change all of them to _ so it would be like

x_assembled_forward.fastq.gz
x(n)_unassembled_reverse.fastq.gz

I thought it would be possible using the simple command:

mv *.assembled.*.fast.gz  *_assembled_*.fastq.gz

…. apparently not! 😀

How can I do that?

Best Answer

If you have perl-rename installed (called rename on Debian, Ubuntu and other Debian-derived systems), you can do:

rename -n 's/\./_/g; s/_fastq_gz/.fastq.gz/' *fastq.gz

That will first replace all . with _ and then replace the final _fastq_gz with .fastq.gz.

The -n causes it to only print the changes it would do, without actually renaming the files. Once you're sure this does what you want, remove the -n to actually rename them:

rename  's/\./_/g; s/_fastq_gz/.fastq.gz/' *fastq.gz
Related Question