Link to home
Start Free TrialLog in
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

Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

please try this

set /A Counter=%Counter%+1

Open in new window

Avatar of Sharp2b

ASKER

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
Avatar of Qlemo
Qlemo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Sharp2b

ASKER

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.