查找环境变量是否包含子字符串

18

我需要在Windows批处理文件中查找某个环境变量(例如Foo)是否包含一个子字符串(例如BAR)。是否有办法仅使用批处理命令和/或默认与Windows安装的程序/命令来完成这一操作?

例如:

set Foo=Some string;something BAR something;blah

if "BAR" in %Foo% goto FoundIt     <- What should this line be? 

echo Did not find BAR.
exit 1

:FoundIt
echo Found BAR!
exit 0

为了使这个简单的批处理文件输出"Found BAR",上面标记的行应该是什么?

3个回答

32

当然,只需使用好老的findstr:

echo.%Foo%|findstr /C:"BAR" >nul 2>&1 && echo Found || echo Not found.

你可以选择在那里分支,而不是使用echo输出,但我认为如果你需要基于多个语句来执行此操作,下面的方法会更容易一些:

echo.%Foo%|findstr /C:"BAR" >nul 2>&1
if not errorlevel 1 (
   echo Found
) else (
    echo Not found.
)

编辑:同时注意jeb的解决方案,这个方案更加简洁,但在阅读时需要额外的思考来理解它实际上做了什么。


如果%Foo%变量包含分号;,就像%PATH%变量一样,那么你的解决方案是可行的。您还可以使用/I参数将搜索不区分大小写。通过将BAR替换为%SEARCH_TERM%,您还可以搜索另一个变量的内容。非常有用! - ixe013

27
findstr的解决方法有效,但它有点慢,而且我认为使用findstr是杀鸡焉用牛刀。
简单的字符串替换也可以起作用。
if "%foo%"=="%foo:bar=%" (
    echo Not Found
) ELSE (
    echo found
)

或者使用相反的逻辑

if NOT "%foo%"=="%foo:bar=%" echo FOUND
如果比较的两个值不相等,那么变量中的文本必须存在,因此搜索文本将被移除。
一段小示例,展示该行如何被扩展。
set foo=John goes to the bar.
if NOT "John goes to the bar."=="John goes to the ." echo FOUND

+1. 是的,有时候我对findstr的性能也感到有些不满(在我的大数库中尤为明显,因为在计算过程中需要多次检查数字的正确格式 - 这很快就会累加)。我没有想到那个解决办法。 - Joey
1
@Joey:如果内容中包含引号,那么延迟扩展应该是解决方案。 - jeb
尝试使用PATH解决此问题,但不起作用。http://stackoverflow.com/questions/38695620/windows-check-string-contains-another-not-working - Billa
@Billa,它失败了,因为你的问题不同。你试图检查一个变量的内容是否是另一个变量的一部分。 - jeb
我尝试了其他可能的解决方案,但它们都对我无效。尝试使用findstr /m "D:\Package\Libraries\Lib" %PATH% if %errorlevel%==1 add env path - Billa
显示剩余3条评论

2
我为了实现脚本的良好集成编写了这个函数。代码看起来更好,也更容易记忆。这个函数基于Joey在这个页面上的答案。我知道它不是最快的代码,但它似乎非常适合我需要做的事情。
只需将函数代码复制到您的脚本末尾,就可以像这个示例一样使用它:
示例:
set "Main_String=This is just a test"
set "Search_String= just "

call :FindString Main_String Search_String

if "%_FindString%" == "true" (
    echo String Found
) else (
    echo String Not Found
)

请注意,在“FindString”函数之后,我们不需要在变量中添加任何%字符。这在我们的自定义函数内部自动完成。
(这是批处理函数的一个好的解决方案,允许我们轻松地使用包含空格的值作为函数参数,而无需关心引号或其他任何内容。)

功能:

:FindString

rem Example:
rem 
rem set "Main_String=This is just a test"
rem set "Search_String= just "
rem 
rem call :FindString Main_String Search_String
rem 
rem if "%_FindString%" == "true" echo Found
rem if "%_FindString%" == "false" echo Not Found

SETLOCAL

for /f "delims=" %%A in ('echo %%%1%%') do set str1=%%A
for /f "delims=" %%A in ('echo %%%2%%') do set str2=%%A

echo.%str1%|findstr /C:"%str2%" >nul 2>&1
if not errorlevel 1 (
   set "_Result=true"
) else (
   set "_Result=false"
)

ENDLOCAL & SET _FindString=%_Result%
Goto :eof

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接