How to change one part of file name in bash?

Viewed 72

I am fairly new to Bash and don't know how to do much. I have a series of folder and within those folders I have a few files, for example in the first folder I might have:

  • file1_0.extension
  • file1_1.extension
  • file1_2.extension
  • ...
  • file1_9.extension
  • file1_10.extension
  • file1_11.extension
  • ...

And so on. What I would like to do is write a Bash script that goes through all folders and change the first 10 filenames so that it instead looks like this:

  • file1_00.extension
  • file1_01.extension
  • file1_02.extension
  • ...
  • file1_09.extension
  • file1_10.extension
  • file1_11.extension
  • ...

Would anyone be able to explain how this can be done in Bash? I am fairly new to Bash scripting

1 Answers

You can use "rename" command to do the trick.

First, using "rename -v" to see whether it's installed, if not, you can use this command for Ubuntu

sudo apt install rename

Or for SUSE

zypper install rename

Then simply use

rename -e 's/file1_([0-9]).extension/file1_0$1.extension/' -- *.extension

This can rename the files as you'd like to.

Related