19

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,678
  • 1
  • 20
  • 29

3 Answers3

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,678
  • 1
  • 20
  • 29
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
  • 50,835
  • 10
  • 55
  • 88
  • 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
3

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
  • 10,854
  • 7
  • 47
  • 46