NewbieCoder
NewbieCoder

Reputation: 706

Batch Coding For loop to create files with different names

I'm new to Batch coding, so please go easy.

Please consider the following code:

FOR /L %%G IN (1,1,20) DO (break>"C:\New folder\%%G+1.txt")

I'm trying to create text files with the above code, but I'm getting 1+1, 2+1, 3+1.. and so on.

Is there a way to not touch the parameters, but to increase the parameter in %%G+1? Instead of outputting as a string, it gives me a number.

Please guide me. thanks

Update: I tried this code below

:MakeTextFiles
setlocal enabledelayedexpansion
set "var=1"
FOR /L %%G IN (1,1,20) DO 
(       
    set /a "var=%var%+1" 
    break>"C:\New folder\!var!.txt"
)
EXIT /B

But it's not working.

Upvotes: 0

Views: 58

Answers (2)

CodeMonkey
CodeMonkey

Reputation: 4738

You don't need arithmetic addition here, just change the set you loop over:

FOR /L %%G IN (2,1,21) DO (break>"C:\New folder\%%G.txt")

If you definitely want arithmetic:

setlocal enabledelayedexpansion
FOR /L %%G IN (1,1,20) DO (
set /a var=%%G+1
break>"C:\New folder\!var!.txt")

You need to look here:

calculating the sum of two variables in a batch script

and here delayed expansion

Upvotes: 1

Magoo
Magoo

Reputation: 79982

setlocal enabldelayedexpansion
FOR /L %%G IN (1,1,20) DO 
(
    set /a _new=%%G+1
    break>"C:\New folder\!_new!.txt"
)

Please see hundrds of articles on SO about delayedexpansion

Two problems with your latest change:

The ( must be on the same physical line as the do.

set /a var=!var!+1

or

set /a var=var+1

or

set /a var+=1

set /a accesses the run-time value of var, !var! is the run-time value of var, %var% is the parse-time value of var - the value that it has when the for is encountered.

Upvotes: 1

Related Questions