Batch renaming

When I was doing a timelapse today my camera switched from 9999 to 10000 which resulted in a new filename for the images (IMG_9999.CR2 to IMG_0001.CR2). This will naturally make a huge problem when dealing with lots of images that need to be numerically sorted. If they aren't named correctly most, if not all, video editing software will fail to import the sequence correct. So naturally I didn't like the idea of me renaming hundreds of images just to get an extra number in to the filename.

This is a task for the computer, not my lazy ass.

So I wrote a batch file that would do the job for me. First I sorted out all the .CR2 files I needed to get renamed and then I wrote two batch files. Now I'm no pro in writing windows batch files, but I knew I'd need something similar to a for or foreach loop, so whilst trying to find out what correct syntax is, I found this helpful page. This page basically gave me everything I needed.


* File: imageloop.bat
* The modifier %%f is the variable where the data will be written to,
* (dir *.CR2) is kind of self-explanatory. When we get this information we
* can call the renamer.bat and pass the filename the renamer.bat and pass
* the filename and the extensions as two variables to it.
for %%f IN (dir *.CR2) do call renamer.bat %%~nf %%~xf
* File: renamer.bat
* Now we passed two variables to this file from the imageloop.bat, these
* are called %[Numerical number] or in our case, we sent two variables,
* so they would be %1 and %2.
* First we copy the filename over to a new variable adn then we copy the
* extension, we know we want to add a single digit to the filename so we set
* number.
* Now we need to split up the filename into two variables, in my case it was
* IMG_ and 0001, so I use a substring equal function where I set from where
* I want to begin to where it should end [:~0,4] is start at char 0 and end
* at 4 characters forward from 0, this gives us "IMG_" from filename. To
* get the end of the filename, we do the same but reversed, we start at
* char 4 and end 4 characters forward, this gives us "0001".
* Now we just need to concatenate these variables to form "IMG_10001.CR2",
* which I do at the same time as I throw the rename command.
set filename=%1
set extension=%2
set number=1
set prefilename=%filename:~0,4%
set postfilename=%filename:~4,4%
rename %filename%%extension% %prefilename%%number%%postfilename%%extension%
* Remember to remove these comments if you copy these scripts šŸ™‚
Benjamin Horn
Benjamin Horn
ā€” Developer at Bazooka
A Finnish-German full-stack developer who's worked with a multitude of different technologies throughout the years.
Vaasa, Finland