General Computing
bash rename sed
Updated Fri, 05 Aug 2022 12:01:10 GMT

Mass Rename Files with bash

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?


To protect files with 3 digits already

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

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.

Comments (3)

  • +0 – This could've saved me a step earlier. I've been doing it all with sed, and used ls | grep '[0-9]\{3\}' | sed 's|\(.*\)#0\(.*\)|mv "&" "\1#\2"|' | sh just to make them have two digits, and then did it the way I listed above. — Oct 30, 2011 at 15:20  
  • +0 – I've changed this to the answer, now that I'm learning more about all of this, this is more practical and adaptable. — Nov 08, 2011 at 18:44  
  • +0 – One can use the -v option to printf: printf -v new "file #%03d.ext" $num — Nov 01, 2012 at 22:19