Yazan
Yazan

Reputation: 50

batch: rename files by padding numbers with zeros

I want to rename some files named initialy like this:

KIT0_rawinput_descriptors.m => KIT00_rawinput_descriptors.m
KIT0_rawinput_estimation.m => KIT00_rawinput_estimation.m
KIT0_rawinput_label_kp.m
KIT1_rawinput_descriptors.m => KIT01_rawinput_descriptors.m
KIT1_rawinput_estimation.m
KIT1_rawinput_label_kp.m

I wrote this batch file but it doesn't work it says that there is another file with the same name or file is not found! I am not getting the point! Please help me

setlocal enableextensions enabledelayedexpansion
set idx="xx"
for /l %%x in (0, 1, 1) do (
    Set "Pattern=KIT%%x_"
    Set "Replace=KIT0%%x_"
    for /r %%# in (*!Pattern!*) do (
        Set "File=%%~nx#"
        echo "!File!"
        rem Ren "%%#" "!File:%Pattern%=%Replace%!"
        )
    )
endlocal

Upvotes: 1

Views: 596

Answers (1)

user6811411
user6811411

Reputation:

Albeit you are using delayed expansion your %Replace% is already in an area needing delayed expansion, so you need it twice with a different method:

setlocal enableextensions enabledelayedexpansion
set idx="xx"
for /l %%x in (0, 1, 1) do (
    Set "Pattern=KIT%%x_"
    Set "Replace=KIT0%%x_"
    for /r %%# in (*!Pattern!*) do (
        Set "File=%%~nx#"
        echo "!File!"
        Call Echo Ren "%%#" "%%File:!Pattern!=!Replace!%%"
        )
    )
endlocal

If the output looks OK remove the echo between Call and Ren.

Upvotes: 1

Related Questions