1

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
Yazan
  • 50
  • 6

1 Answers1

1

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.

  • I am not really familiar with batch files! when you say "an area needing delayed expansion" is it because of "for /r %%# in" ? if not so its because of what? The delayed expansion is done using a double percent "%%" ? what is the difference between this expansion symbole"%" and this one"!" thank you very much for the help and your answers – Yazan Jun 30 '17 at 14:45
  • In short: it's the way cmd parses the batch. Variables in area's enclosed in parentheses (code blocks) are evaluated first. If you **set** a variable inside a code block it's new value is thus only retrieved with delayed expansion. In your case `Pattern` and `Replace` are set in a code block and the replace command itself needs delayed expansion to force the actual values and also for the variable File. The pseudo call is an older method here used for the double edelayed expansin. For tdetails on how cmd parses batche see [this Q&A](https://stackoverflow.com/questions/4094699) –  Jun 30 '17 at 14:57
  • may be a [little bit easier to understand](https://stackoverflow.com/a/30284028/2152082)... – Stephan Jun 30 '17 at 15:40
  • Agreed, but this doesn't explain the requirement for twofold delayed expansion. –  Jun 30 '17 at 15:42