4

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%
)
1

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.