Batch file: Find if substring is in string (not in a file)
Yes, you can use substitutions and check against the original string:
if not x%str1:bcd=%==x%str1% echo It contains bcd
The %str1:bcd=%
bit will replace a bcd
in str1
with an empty string, making it different from the original.
If the original didn't contain a bcd
string in it, the modified version will be identical.
Testing with the following script will show it in action:
@setlocal enableextensions enabledelayedexpansion
@echo off
set str1=%1
if not x%str1:bcd=%==x%str1% echo It contains bcd
endlocal
And the results of various runs:
c:\testarea> testprog hello
c:\testarea> testprog abcdef
It contains bcd
c:\testarea> testprog bcd
It contains bcd
A couple of notes:
- The
if
statement is the meat of this solution, everything else is support stuff. - The
x
before the two sides of the equality is to ensure that the stringbcd
works okay. It also protects against certain "improper" starting characters.
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
I usually do something like this:
Echo.%1 | findstr /C:"%2">nul && (
REM TRUE
) || (
REM FALSE
)
Example:
Echo.Hello world | findstr /C:"world">nul && (
Echo.TRUE
) || (
Echo.FALSE
)
Echo.Hello world | findstr /C:"World">nul && (Echo.TRUE) || (Echo.FALSE)
Output:
TRUE
FALSE
I don't know if this is the best way.