Link to home
Create AccountLog in
Avatar of ToddRod_Taylor
ToddRod_TaylorFlag for United States of America

asked on

MS-DOS locate string in multi line text file then set to a variable

I would like to use MS-DOS FIND command (or some other method) in a batch to locate a string from  TEXTFILE.TXT and store it to a variable.  My text file has multiple lines, and the string I search for is always the same "StoreId="   However, it can be on different lines within the text file.  Always in the top 10 lines.  I am after the value of what StoreId equals for the contents of the variable.

Example line from text file: StoreId=st0028
DOS batch variable contents desired: 0028
Avatar of SteveGTR
SteveGTR
Flag of United States of America image

Could try this. I need to test it, but it should work:

@echo off

setlocal

set storeId=

for /f "tokens=1,* delims==" %%a in ('type "%~1" 2^>NUL ^| findstr /i /c:"Storeid="') do if /i "%%a"=="Storeid" set storeId=%%b

echo storeId=%storeId%

Good Luck,
Steve
It works. The processing takes the file name as a parameter to the batch file. So if you named the batch file FindStore.bat you'd say:

FindStore TEXTFILE.TXT

You could further optimize the processing like so:

@echo off

setlocal

set storeId=

for /f "tokens=1,* delims==" %%a in ('type "%~1" 2^>NUL ^| findstr /i /c:"Storeid="') do if /i "%%a"=="Storeid" set storeId=%%b&goto FOUNDIT

echo Didn't find store ID
goto :EIF

:FOUNDIT

echo storeId=%storeId%

Or you could simplify the processing since you've stated that the store ID occurs in the 1st 10 lines:

@echo off

setlocal

set storeId=

for /f "tokens=1,* delims==" %%a in ('type "%~1" 2^>NUL') do if /i "%%a"=="Storeid" set storeId=%%b&goto FOUNDIT

echo Didn't find store ID
goto :EIF

:FOUNDIT

echo storeId=%storeId%
ASKER CERTIFIED SOLUTION
Avatar of SteveGTR
SteveGTR
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of ToddRod_Taylor

ASKER

b&goto FOUNDIT = goto FOUNDIT ?
or should b&goto FOUNDIT be on the same line as the for statement?
SteveGTR,

your final comment works, I forgot to say that I need to chop off the "st" in that variable.  Is that easy to add?   Other than that great!
It worked, thank you for the help!

FYI I answered my own question on my last comment.

I added:
set storeid=%storeid:~-3%
Excellent :)