Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a variable contains another variable within a windows batch file?

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

like image 717
Gary Brunton Avatar asked Jul 11 '13 23:07

Gary Brunton


2 Answers

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)

like image 50
Gary Brunton Avatar answered Sep 21 '22 01:09

Gary Brunton


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.

like image 45
Stephan Avatar answered Sep 22 '22 01:09

Stephan