12

I have the following for loop:

for /l %%a in (1,1,%count%) do (
<nul set /p=" %%a - "

Echo !var%%a!
)

which will display something like this:

1 - REL1206
2 - REL1302
3 - REL1306

I need to create a variable that appends itself based on the number of iterations. Example the variable would look like this after the for loop:

myVar="1, 2, 3"

2 Answers 2

28

example:

@ECHO OFF &SETLOCAL
SET /a count=5
for /l %%a in (1,1,%count%) do call set "Myvar=%%Myvar%%, %%a"
ECHO %Myvar:~2%

..output is:

1, 2, 3, 4, 5
Sign up to request clarification or add additional context in comments.

5 Comments

I wonder where has the first comma gone and what is the point of calling the set operation?
The first comma and space are skipped by the line echo %Myvar:~2% which outputs a substring of %Myvar% starting after the first two characters,
Finally a working code!!! There's a considerable time since I've started to look for this. Thanks!
The "call" does the magic. W/o it doesn't accumulate. I searched a while to find this. But what does this, why is this? The "call" doc says "Calls one batch program from another" ...?
„Batch‟ is magic :-)
10

Use delayed expansion

setlocal enableextensions enabledelayedexpansion
SET OUTPUTSTRING=
for /l %%a in (1,1,%count%) do (
<nul set /p=" %%a - "
Echo !var%%a! 
if .!OUTPUTSTRING!==. (
    SET OUTPUTSTRING=%%a
) ELSE (
    SET OUTPUTSTRING=!OUTPUTSTRING!, %%a
)
)
SET OUTPUTSTRING

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.