Search code examples
windowsbatch-filecmdfindstr

Find text in file and set it as a variable. Batch file


I try to find one line in whole text file. Next I need to set this line as a variable.

When I try do this:

set MY_VARIABLE=findstr /I "MY_TEXT" MY.FILE
echo %MY_VARIABLE%

The result of echo is findstr /I "MY_TEXT" MY.FILE, but I want to see result of this command line instead.

When I try do this – first enter in cmd:

for /F "delims=" %%a in ('findstr /I "MY_TEXT" MY.FILE') do set "batToolDir=%%a"

then enter in cmd:

echo "%batToolDir%"

I see an error:

the %%a variable is unsuspected

When I make a file SCRIPT.bat:

@echo off 
for /F "delims=" %%a in ('set MY_VARIABLE=findstr /I "MY_TEXT" MY.FILE') do set "batToolDir=%%a"
echo "%batToolDir%"

I get this:

""

What is wrong? How to make this?


Solution

  • Almost done

    For command line

    for /F "delims=" %a in ('findstr /I "MY_TEXT" MY.FILE') do set "batToolDir=%a"
    

    For batch file double the percent signs

    for /F "delims=" %%a in ('findstr /I "MY_TEXT" MY.FILE') do set "batToolDir=%%a"