Bash – How to Mass Rename Files with Bash

bashrenamesed

I've got a bunch of numbered files like this:

file #01.ext
file #02.ext
file #03.ext
file #04.ext
file #05.ext

And what I want is to make them all have three digits (two leading 0's) instead of one, so;

file #001.ext
file #002.ext
file #003.ext
file #004.ext
file #005.ext

My thought is to use sed to replace the # with #0 (which in my case is good enough, there are no files over #99 yet). All the files are in the same folder, how would I do that?

Best Answer

To protect files with 3 digits already

for f in "file #"*.ext; do
  num=${f#file #}
  num=${num%.ext}
  new=$(printf "file #%03d.ext" $num)
  echo mv "$f" "$new"
done

This will display in the console the commands to execute, but not actually rename the files.

Once you are happy with what it intends to do, you can make it rename the files by removing the word echo and re-running it.

Related Question