i have 2 batch files a.bat , b.bat. a.bat calls b.bat , b.bat prints sentence screen. how can check sentence see if contains word , if contains set variable. example
sentance: hello, how today? if %sentance contains% hello set var=hello if %sentance contains% hi set var=hi
there may more 1 sentance on screen want check displayed sentance.
here's have.
for /f delims^=^ eol^= %%i in ('b.bat') 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 last line "this message hello"
echo string , search keyword:
set sentence=hello, how you? echo %sentence%|findstr /i "\<hello\>">nul && set "var=hello" echo %sentence%|findstr /i "\<hi\>">nul && set "var=hi"
\<
, \>
means "word boundaries", avoids false positives (chinese, chello,...)
>nul
redirects found string nirvana keep screen clear.
&&
executes set
command only, if previous command (findstr
) successful.
edit
based on last comment, understand: a.bat
calls b.bat
. b.bat
writes several lines, , a.bat
wants last of them (i hope, got right).
to last line of b.bat
, use:
for /f delims^=^ eol^= %%i in ('b.bat') set lastline=%%i echo said: %lastline% set "var=" echo %lastline%|findstr /i "\<hello\>">nul && set "var=hello" echo %lastline%|findstr /i "\<hi\>">nul && set "var=hi" echo %lastline%|findstr /i "\<hola\>">nul && set "var=hola" echo/%var%
but there little problem: for
captures output of b.bat
instead of showing screen. (especially prompt of set /p
- don't know, when or input). work around that, force b.bat
write screen (>con
writes directly screen). basically, b.bat
should this:
@echo off echo line gets captured a.bat >con echo line goes directly screen >con set /p "input=give me input: " echo %input%.
note: used eol
-trick aschipfl's answer, because (although looks ugly) works both "
, ;
, problematic "standard way" ("delims= eol="
). of course still isn't foolproof (for example &
still makes problems)
Comments
Post a Comment