Search code examples
batch-filestring-concatenation

concatenating incrementing counter to string variable in batch file


I have a script to create some files using format random_tests_0, random_tests_1 but my variable is not working when adding to the string of filename.

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
set /A num=0
for %%a in (.\gpc_cfgs\*) do ( 
    ECHO !num!
    set filename = random_tests_!num!
    ECHO !filename!
    set /A num+=1
)
OUTPUT:
0
random_tests_0
1
random_tests_0

EXPECTED OUTPUT:
0
random_tests_0
1
random_tests_1

Solution

  • When setting a variable spaces either side of the = are included in both the name and the variable. You should be able to fix that by using !filename ! although the value would still begin with a possibly unwanted space too!.

    The recommended syntax is Set "VariableName=VariableValue", thus:

    @Echo Off
    SetLocal EnableDelayedExpansion
    Set "num=0"
    For %%A In ("gpc_cfgs\*") Do (
        Echo !num!
        Set "filename=random_tests_!num!"
        Echo !filename!
        Set /A num+=1
    )
    

    This should output the same number of !filenames! as you have files inside gpc_cfgs.