0

I would like to split a word and add plus one on number. ex) from dev_111 to dev_112 So I edit batch file like below but it doesn't work on first and second execute but third.

Batch script

@echo off

FOR /f "tokens=1,2 delims=_" %%a IN ("dev_111") do (
    echo %%a
    echo %%b
    SET /a c=%%b+1
    echo %c%
    SET d=%%a_%c%
    echo Create folder %d%?
)

Result

C:\Users\aaa>bbb_.bat
dev
111
Echo is not defined
Create folder ?

C:\Users\aaa>bbb_.bat
dev
111
112
Create folder dev_?

C:\Users\aaa>bbb_.bat
dev
111
112
Create folder dev_112?

Would anyone resolve this? I don't have any clue why this happening..

1 Answers1

0

You need delayd expansion:

@echo off
setlocal enableextensions enabledelayedexpansion

FOR /f "tokens=1,2 delims=_" %%a IN ("dev_111") do (
    echo %%a
    echo %%b
    SET /a c=%%b+1
    echo !c!
    SET d=%%a_!c!
    echo Create folder !d!?
)

endlocal

The entire for loop is read and variables are substituted before any of it is executed. That means things like %c% will be substituted with the value they held before the loop, meaning anything you assign to them within the loop is not available to you.

By using delayed expansion and the ! substitution character, the substitutions take place when the line is evaluated within the loop.


The reason your original script acts differently on subsequent runs is because the variables are being set, they're just not seen until after the for loop finishes. That means they'll be in the environment (ese echo %d% after running, for example), ready for the next time your script runs (though, if they change each time, you'll always have the values set from the previous run).

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953