I have 2 batch files a.bat and b.bat. a.bat calls b.bat and b.bat prints a sentence to the screen. How can I check that sentence to see if it contains a word and if it contains a set it as a variable. For example
Sentance: Hello, how are you today?
If %Sentance contains% Hello set var=Hello
If %Sentance contains% Hi set var=hi
There may be more than one Sentance on the screen so I want to check the most recently displayed sentance.
Here's what I have.
for /f delims^=^ eol^= %%i in ('b.bat') do set lastline=%%i
set "var="
echo %lastline%|findstr /i "\<hi\>">nul && set "var=hi"
IF ERRORLEVEL 1 (GOTO NEXT0) ELSE (GOTO FOUND)
:NEXT0
echo %lastline%|findstr /i "\<hello\>">nul && set "var=hello"
IF ERRORLEVEL 0 (GOTO NEXT1) ELSE (GOTO FOUND)
:NEXT1
echo %lastline%|findstr /i "\<hola\>">nul && set "var=hola"
IF ERRORLEVEL 0 (GOTO NEXT2) ELSE (GOTO FOUND)
:found
echo %var%
pause
The code doesn't work if the last line is something like "this is a message hello"
Stephan's answer already shows how to find specific words in the output of the called batch file
b.bat
.To check the output of
b.bat
in the callera.bat
, you can do the following:Supposing
b.bat
contains the following:a.bat
might look like this:This pipes the output of
b.bat
intofindstr
, which uses multiple search strings, then its output is captured by afor /F
loop, which assigns the output to the variableFOUND
.Which gets what the user typed and mimics cmd processing (press Ctrl + C to stop it). Use set to manipulate the text.
You can use a
for
loop to break up text.echo the string and search for the keyword:
\<
and\>
means "Word boundaries", this avoids false positives (Chinese, Chello,...)>nul
redirects the found string to nirvana to keep the screen clear.&&
executes theset
command only, if previous command (findstr
) was successful.Edit
Based on your last comment, I understand:
a.bat
callsb.bat
.b.bat
writes several lines, anda.bat
wants to get the last of them (I hope, I got that right).to get the last line of
b.bat
, use:But there is a little problem:
for
captures the output ofb.bat
instead of showing it to the screen. (Especially the prompt ofset /p
- so you don't know, when or what to input). To work around that, forceb.bat
to write to screen (>con
writes directly to screen). So basically,b.bat
should look like this:Note: I used the
eol
-trick from aschipfl's answer, because (although it looks ugly) this works even for both"
and;
, which are problematic with the "standard way" ("delims= eol="
). Of course this still isn't foolproof (for example&
still makes problems)