Yeung
Yeung

Reputation: 2231

variable in FOR /F

I am new to write batch file I have a simple.txt and its content:

aaa 1
bbb 2
ccc 3
bbb 4
aaaa 5
aaccdd 7

and run the batch file:

@echo off
FOR /F "tokens=2 delims= " %%a in ('FindStr "aa" ^"simple.txt^"') DO (
    SET TEMP_VAR=%%a
    echo %TEMP_VAR%
)

The result is

7
7
7

But what I expect is

1
5
7

Why does this happen? What I am thinking it is C-like or Java-like for loop. Is it really different from them?

Upvotes: 1

Views: 613

Answers (1)

dbenham
dbenham

Reputation: 130819

Classic problem for a person learning batch :-)

The entire FOR loop, including the contents of the parentheses, is parsed prior to the loop executing. Normal %TEMP_VAR% expansion takes place as part of the parsing, so the value you see is the value that existed before the loop is executed.

The solution is simple: Add setlocal enableDelayedExpansion at the top, and use !TEMP_VAR! instead.

@echo off
setlocal enableDelayedExpansion
FOR /F "tokens=2 delims= " %%a in ('FindStr "aa" ^"simple.txt^"') DO (
    SET TEMP_VAR=%%a
    echo !TEMP_VAR!
)

The HELP documentation provides a description of the problem. Type HELP SET or SET /? from the command line. The description of normal vs. delayed expansion is about 2/3 down from the top.

Upvotes: 3

Related Questions