How to concatenate number and string in for loop? I've tried like this but it doesn't work:
SET PATH=C:\file
FOR /L %%x IN (1,1,5) DO (
SET "NUM=0%%x"
SET VAR=%PATH%%NUM%
ECHO %VAR%
)
How to concatenate number and string in for loop? I've tried like this but it doesn't work:
SET PATH=C:\file
FOR /L %%x IN (1,1,5) DO (
SET "NUM=0%%x"
SET VAR=%PATH%%NUM%
ECHO %VAR%
)
Modify your code like this:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET PATH=C:\file
FOR /L %%x IN (1,1,5) DO (
SET "NUM=0%%x"
SET VAR=%PATH%!NUM!
ECHO !VAR!
)
You always have to use SETLOCAL ENABLEDELAYEDEXPANSION
and !...!
instead of %...%
when working with variables which are modified inside a loop.
You'll need delayed expansion to accomplish that:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET FILEPATH=C:\file
FOR /L %%x IN (1,1,5) DO (
SET "VAR=%FILEPATH%0%%x"
ECHO !VAR!
)
ENDLOCAL & SET VAR=%VAR%
You do not need the interim variable NUM
, you can concatenate the string portions immediately.
You should never change variable PATH
as this is used by the system. Hence I changed it to FILEPATH
.
Since SETLOCAL
creates a new localised environment block, all variables defined or changed in there cannot be seen outside of that block. However, the last line in the above code demonstrates how the last concatenated value can be passed beyond ENDLOCAL
.