In a batch file, I have a string abcdefg
. I want to check if bcd
is in the string.
Unfortunately it seems all of the solutions I\'m find
You can pipe the source string to findstr
and check the value of ERRORLEVEL
to see if the pattern string was found. A value of zero indicates success and the pattern was found. Here is an example:
::
: Y.CMD - Test if pattern in string
: P1 - the pattern
: P2 - the string to check
::
@echo off
echo.%2 | findstr /C:"%1" 1>nul
if errorlevel 1 (
echo. got one - pattern not found
) ELSE (
echo. got zero - found pattern
)
When this is run in CMD.EXE, we get:
C:\DemoDev>y pqrs "abc def pqr 123"
got one - pattern not found
C:\DemoDev>y pqr "abc def pqr 123"
got zero - found pattern
Better answer was here:
set "i=hello " world"
set i|find """" >nul && echo contains || echo not_contains
If you are detecting for presence, here's the easiest solution:
SET STRING=F00BAH
SET SUBSTRING=F00
ECHO %STRING% | FINDSTR /C:"%SUBSTRING%" >nul & IF ERRORLEVEL 1 (ECHO CASE TRUE) else (ECHO CASE FALSE)
This works great for dropping the output of windows commands into a boolean variable. Just replace the echo with the command you want to run. You can also string Findstr's together to further qualify a statement using pipes. E.G. for Service Control (SC.exe)
SC QUERY WUAUSERV | findstr /C:"STATE" | FINDSTR /C:"RUNNING" & IF ERRORLEVEL 1 (ECHO case True) else (ECHO CASE FALSE)
That one evaluates the output of SC Query for windows update services which comes out as a multiline text, finds the line containing "state" then finds if the word "running" occurs on that line, and sets the errorlevel accordingly.
I'm probably coming a bit too late with this answer, but the accepted answer only works for checking whether a "hard-coded string" is a part of the search string.
For dynamic search, you would have to do this:
SET searchString=abcd1234
SET key=cd123
CALL SET keyRemoved=%%searchString:%key%=%%
IF NOT "x%keyRemoved%"=="x%searchString%" (
ECHO Contains.
)
Note: You can take the two variables as arguments.
The solutions that search a file for a substring can also search a string, eg. find
or findstr
.
In your case, the easy solution would be to pipe a string into the command instead of supplying a filename eg.
case-sensitive string:
echo "abcdefg" | find "bcd"
ignore case of string:
echo "abcdefg" | find /I "bcd"
IF no match found, you will get a blank line response on CMD and %ERRORLEVEL% set to 1
ECHO %String%| FINDSTR /C:"%Substring%" && (Instructions)