Page 1 of 1

For /F and set (Solved)

Posted: 31 May 2012 16:41
by ThinAir
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.

Re: For /F and set

Posted: 31 May 2012 19:39
by foxidrive
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

Re: For /F and set

Posted: 31 May 2012 21:59
by Aacini
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!
)

Re: For /F and set

Posted: 01 Jun 2012 11:26
by ThinAir
Thank you Aacini.