For /F and set (Solved)

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
ThinAir
Posts: 3
Joined: 31 May 2012 16:25

For /F and set (Solved)

#1 Post by ThinAir » 31 May 2012 16:41

Windows XP script.
RESSTRING is a string
RESLIST is a file

Within a script I have:
for /f "delims=" %%a in ('findstr "%RESSTRING%" %RESLIST%') do @set RESLINE=%%a
echo %RESLINE%


The set command doesn't work as I expect it to.
echo %RESLINE% is empty.
echo %%a returns the expected sting (when I replace "@set RESLINE=%%a" with "echo %%a".

The same command executed at the command line works fine.
for /f "delims=" %a in ('findstr "%RESSTRING%" %RESLIST%') do @set RESLINE=%a
echo %RESLINE% returns the expected sting.
echo %%a returns the expected sting.

Any help would be appreciated.
Last edited by ThinAir on 08 Jun 2012 09:20, edited 1 time in total.

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: For /F and set

#2 Post by foxidrive » 31 May 2012 19:39

It works fine. Check if your filename contains spaces or special characters and that will need double quoting.

Code: Select all

@echo off
set RESSTRING=a
set RESLIST="file.txt"
echo a>file.txt

for /f "delims=" %%a in ('findstr "%RESSTRING%" %RESLIST%') do @set RESLINE=%%a
echo %RESLINE%
pause

Aacini
Expert
Posts: 1927
Joined: 06 Dec 2011 22:15
Location: México City, México
Contact:

Re: For /F and set

#3 Post by Aacini » 31 May 2012 21:59

If within a script you have these two lines:

Code: Select all

for /f "delims=" %%a in ('findstr "%RESSTRING%" %RESLIST%') do @set RESLINE=%%a
echo %RESLINE%
... for themselves alone, it MUST work ok.

However, if you have these lines inside an IF or FOR command:

Code: Select all

if %var% equ value (
   for /f "delims=" %%a in ('findstr "%RESSTRING%" %RESLIST%') do @set RESLINE=%%a
   echo %RESLINE%
)

... then the echo %RESLINE% show the value that RESLINE had before enter the IF command.

To solve this problem you must use Delayed Expansion, that is, insert an appropiate setlocal command at beginning and replace percent-signs by exclamation marks:

Code: Select all

setlocal EnableDelayedExpansion
if %var% equ value (
   for /f "delims=" %%a in ('findstr "%RESSTRING%" %RESLIST%') do @set RESLINE=%%a
   echo !RESLINE!
)

ThinAir
Posts: 3
Joined: 31 May 2012 16:25

Re: For /F and set

#4 Post by ThinAir » 01 Jun 2012 11:26

Thank you Aacini.

Post Reply