找出一个环境variables是否包含一个子string

我需要找出一个特定的环境variables(比方说Foo)是否包含了一个windowsbatch file中的一个子string(比方说BAR)。 有没有办法做到这一点只使用batch file命令和/或程序/默认安装的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 

上面的标记行是为了使这个简单的batch file打印“Found BAR”?

当然,只要使用好旧的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的解决方案 ,以及更简洁,虽然它需要一个额外的心理步骤来弄清楚它在阅读时做什么。

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 

@mythofechelon:%var:str =%部分从var中删除str 。 所以如果var在等式左边包含str ,它将在右边被删除 – 因此,如果在var中找到str ,或者如果str中没有出现str,则等式将导致“false”。

我写了一个很好的脚本集成函数。 代码看起来更好,也更容易记住。 这个函数是基于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 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