如何检查一个变量是否包含 Windows 批处理文件中的另一个变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17605406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I check if a variable contains another variable within a windows batch file?
提问by Gary Brunton
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
我希望输出是 YES 后跟 NO
回答by Gary Brunton
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.
我从以下答案中得到了基本想法,但它不是通过变量搜索,所以它并不完全是我想要的。
回答by Stephan
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.
所述/
的输出防止Echo is ON
或Echo is OFF
情况%variable1%
是空的。
回答by JBE
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 :
如果你尝试使用set variable1="C:\Users\My Name\"
,你最终会得到一个错误:
'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
)