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"
jeb
  • 78,592
  • 17
  • 171
  • 225
Brian
  • 319
  • 1
  • 5
  • 13

2 Answers2

27

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
Endoro
  • 37,015
  • 8
  • 50
  • 63
  • I wonder where has the first comma gone and what is the point of calling the set operation? – Val Apr 26 '14 at 18:03
  • 3
    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, – thomasrutter Mar 17 '16 at 05:12
  • Finally a working code!!! There's a considerable time since I've started to look for this. Thanks! – Fábio Amorim Jan 22 '21 at 11:47
  • 1
    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" ...? – kxr Dec 15 '22 at 15:04
  • „Batch‟ is magic :-) – Endoro Dec 15 '22 at 20:08
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
springer38
  • 101
  • 2