0

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.

3
  • 1
    read again about delayed expansion and "The ( must be on the same physical line as the do" from Magoos answer. Commented Apr 15, 2016 at 7:52
  • Got it! Thanks. Still new to this. So there might be some errors on syntax. Commented Apr 15, 2016 at 8:13
  • yeah - batch syntax isn't consistent and sometimes not very intuitive. Don't mind - the day you don't produce syntax errors any more is far far far away :) Commented Apr 15, 2016 at 8:20

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

4 Comments

I do not want to touch the parameter.
I added a link to the arithmetic answer.
additionally you'll need delayed expansion
Thank you Stephan, you're right. I amended the answer.

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.