如何检查变量是否包含Windows批处理文件中的另一个变量?

时间:2013-07-11 23:46:56

标签: windows 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
)

我希望输出为YES,然后是NO

3 个答案:

答案 0 :(得分:19)

我已通过以下

解决了这个问题
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

我从以下答案中得到了基本的想法,但它没有按变量搜索,所以它并不完全是我想要的。

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

答案 1 :(得分:5)

另一种方式:

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

如果/为空,则Echo is ON会阻止Echo is OFF%variable1%的输出。

答案 2 :(得分:1)

Gary Brunton的回答对我不起作用。

如果您尝试使用set variable1="C:\Users\My Name\",则最终会出现错误:

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

根据Find out whether an environment variable contains a substring调整此答案,我最终得到了:

echo.%variable1%|findstr /C:"%variable2%" >nul 2>&1
if not errorlevel 1 (
   echo Found
) else (
   echo Not found
)
相关问题