Avatar of Sharp2b
Sharp2bFlag for Sweden asked on

How to increment counter variable in "DOS" batch file

I try to create a batch file to run under Windos XP in a command window (or just double clicking the BAT file).

The intention is to take all files with a given extension, concatenate them and add some extra information "between the files". To do this, I need to add a counter value like 1 for the first file, 2 for the second and so on. I have managed to solve all other problems to output what I need but the counter variable is not updated as long as I'm inside the FOR loop. See the attached code example. Put it in a BAT file and run it to see the problem. The last echo after the FOR loop gives the correct value.

Any hints are much appreciated.
@echo off
 
set /A Counter=1
 
echo Initial value of Counter: %Counter%
echo.
 
for %%f in (*.*) do (
	echo File found: %%f
	echo Counter Before increment: %Counter%
	set /A Counter+=1
	echo Counter After Increment: %Counter%
	echo.
)
 
echo Counter after for loop: %Counter%

Open in new window

Microsoft DOSWindows XP

Avatar of undefined
Last Comment
Sharp2b

8/22/2022 - Mon
Guy Hengel [angelIII / a3]

please try this

set /A Counter=%Counter%+1

Open in new window

ASKER
Sharp2b

Thanks for a quick reply but that doesn't work.
The "Counter After Increment" is still 1 for all iterations and now the "Counter after for loop" has the value of 2 when the script ends.
ASKER CERTIFIED SOLUTION
Qlemo

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
Sharp2b

Great, thanks a lot!!!
That was not obvious at all to me, I didn't even know one could use the "!" around variables and I spent several hours Googling for this.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck