Search code examples
batch-filerenaming

Batch file renaming with a number with fitting 00 prefix


So I have lots of mp3 files on my windows 10 computer which I want to rename with a fitting zero prefix EG rename "mysong1.mp3" to "mysong001.mp3" this batch file I found works fine until the 10th file:

@echo off 
setlocal EnableDelayedExpansion 
set i=0 
for %%a in (*.mp3) do (
    set /a i+=1
    ren "%%a" "mysong00!i!.new" 
)
ren *.new *.mp3

after the 9th file I get "mysong0010.mp3", "mysong0011.mp3" etc and after the 99th file "mysong00100.mp3". What I want is "mysong010.mp3", "mysong100.mp3" etc. I have done some research on if statements and the likes in batch files but I couldn't quite get the hang of it.

So my question is: How can I make it work like I want it to?

I don't want to use some kind of third party program, I want to be able to do this myself.


Solution

  • Just a slight change is all you need.

    @echo off 
    setlocal EnableDelayedExpansion 
    set i=0 
    for %%a in (*.mp3) do (
        set /a i+=1
        set num=00!i!
        ren "%%a" "mysong!num:~-3!.new"
    )
    ren *.new *.mp3