20

Assuming the following batch file

set variable1=this is variable1
set variable2=is
set variable3=test

if variable1 contains variable2 (
    echo YES
) else (
    echo NO
)

if variable1 contains variable3 (
    echo YES
) else (
    echo NO
)

I want the output to be a YES followed by a NO

Gary Brunton
  • 1,840
  • 1
  • 22
  • 33

4 Answers4

22

I've resolved this with the following

setLocal EnableDelayedExpansion

set variable1=this is variable1
set variable2=is
set variable3=test

if not "x!variable1:%variable2%=!"=="x%variable1%" (
    echo YES
) else (
    echo NO
)

if not "x!variable1:%variable3%=!"=="x%variable1%" (
    echo YES
) else (
    echo NO
)

endlocal

I got the basic idea from the following answer but it wasn't searching by a variable so it wasn't completely what I was looking for.

Batch file: Find if substring is in string (not in a file)

Community
  • 1
  • 1
Gary Brunton
  • 1,840
  • 1
  • 22
  • 33
6

another way:

echo/%variable1%|find "%variable2%" >nul
if %errorlevel% == 0 (echo yes) else (echo no)

the / prevents output of Echo is ON or Echo is OFF in case %variable1% is empty.

Stephan
  • 53,940
  • 10
  • 58
  • 91
  • This fails for variable1=`/?`, variable1=`on`, and variable1=`off`. Consider `echo foobar %variable1%|find "%variable2%" >nul`, which does fail for variable2=foobar. – GKFX Sep 21 '13 at 15:36
4

Gary Brunton's answer did not work for me.

If you try with set variable1="C:\Users\My Name\", you will end up with an error :

 'Name\""' is not recognized as an internal or external command

Adapting this answer Find out whether an environment variable contains a substring, I ended up with :

echo.%variable1%|findstr /C:"%variable2%" >nul 2>&1
if not errorlevel 1 (
   echo Found
) else (
   echo Not found
)
Community
  • 1
  • 1
JBE
  • 11,917
  • 7
  • 49
  • 51
0

The following is based on JBEs answer in this thread. It distinguishes empty/undefined variables.

if not defined VARIABLE1 (echo VARIABLE1 undefined) & goto proceed
if not defined VARIABLE2 (echo VARIABLE2 undefined) & goto proceed
echo %VARIABLE1% | find "%VARIABLE2%" > nul
if ERRORLEVEL 1 (echo Not found) & goto proceed
echo Found
:proceed

If the value of VARIABLE1 contains parentheses, e.g. the value C:\Program Files (x86), then the parentheses may be interpreted as a distinct command rather than echoed, causing an error. Substrings like (x86) can be escaped with carets for purposes of echoing properly, e.g.:

SET V1_DISPLAY=%VARIABLE1%
if /i "%V1_DISPLAY:(x86)=%" NEQ "%V1_DISPLAY%" set V1_DISPLAY=%V1_DISPLAY:(x86)=^^(x86^^)%
echo %V1_DISPLAY% | find "%VARIABLE2%" > nul

The second statement, above, can be read as follows:

If replacing substring (x86) with nothing makes a difference, then (x86) is present, so replace any occurrence of (x86) with ^^(x86^^), where each pair of carets represent an escaped single caret.

MikeOnline
  • 994
  • 11
  • 18