1.

Solve : how to use expression in for loop?

Answer»

Hi Guys,

I have the below script. My aim is to add 1 to variable count in each ITERATION of the for loop. So, if temp.txt has 10 LINES, count will be 10 finally.

set count=1

for /f "eol=v" %%f in (temp.txt) do (
   set /A count = %count% + 1
   echo %count%
)

But I always get count value is 1. I know the statement "set /A count = %count% + 1" is not correct but don't know how to FIX it.

Anybody can help me on this?Try this:

Code: [Select]echo off
cls
setlocal enabledelayedexpansion

for /f "eol=v" %%f in (temp.txt) do (
   set /A count +=1
   echo !count!
) Quote from: crest.boy on October 17, 2011, 02:06:36 AM

I know the statement "set /A count = %count% + 1" is not correct but don't know how to fix it.

set /A count=%count%+1
set /A count+=1

are equivalent but in a loop you need to USE delayed expansion (exclamation marks instead of percent signs) in the long form

set /A count=!count!+1

(best to omit spaces)



 (google for zillions of explanations)
Quote from: Salmon Trout on October 17, 2011, 08:22:20 AM
set /A count=%count%+1
set /A count+=1

are equivalent but in a loop you need to use delayed expansion (exclamation marks instead of percent signs) in the long form

set /A count=!count!+1


Set /A count=count+1 is also equivalent both inside and outside of a loop, delayed expansion not necessary for a Set /A command LINE..

A little demo:

Code: [Select]echo off
setlocal
cls

for /l %%1 in (1,1,20) do (
    set /a count=count+1
    set /a cntr=cntr+1
    set /a number=count+cntr
    )
    set /a number=number+100
    echo Number=%number%

Quote from: Dusty on October 19, 2011, 12:57:35 AM
Set /A count=count+1 is also equivalent both inside and outside of a loop, delayed expansion not necessary for a Set /A command line..

Right. You can use both the long and short form set /a notations in a loop without delayed expansion, and the final value after the loop is exited will be correct, but delayed expansion is definitely necessary if you want to, er, expand the variable inside the loop.


Discussion

No Comment Found