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.
For /F and set (Solved)
Moderator: DosItHelp
For /F and set (Solved)
Last edited by ThinAir on 08 Jun 2012 09:20, edited 1 time in total.
Re: For /F and set
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
If within a script you have these two lines:... for themselves alone, it MUST work ok.
However, if you have these lines inside an IF or FOR command:
... 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
for /f "delims=" %%a in ('findstr "%RESSTRING%" %RESLIST%') do @set RESLINE=%%a
echo %RESLINE%
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!
)