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
  • 74,839
  • 15
  • 166
  • 215
Brian
  • 199
  • 1
  • 4
  • 12

2 Answers2

26

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
  • 35,920
  • 8
  • 49
  • 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
9

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
  • 91
  • 1