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

LCC*_*LCC 15 windows batch-file

我需要找出一个特定的环境变量(让我们说Foo)在一个Windows批处理文件中是否包含子字符串(比如说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
Run Code Online (Sandbox Code Playgroud)

上面标记的行应该使这个简单的批处理文件打印"Found BAR"?

Joe*_*oey 27

当然,只需使用好的旧发现者:

echo.%Foo%|findstr /C:"BAR" >nul 2>&1 && echo Found || echo Not found.
Run Code Online (Sandbox Code Playgroud)

而不是echo你也可以在那里分支,但我想如果你需要多个语句基于以下更容易:

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

编辑:记下jeb的解决方案,它更简洁,虽然它需要一个额外的心理步骤来弄清楚它在阅读时的作用.


jeb*_*jeb 24

findstr解决方案的工作,这是一个有点慢,在我和意见findstr你打破在车轮上的蝴蝶.

一个简单的字符串替换也应该工作

if "%foo%"=="%foo:bar=%" (
    echo Not Found
) ELSE (
    echo found
)
Run Code Online (Sandbox Code Playgroud)

或者使用反逻辑

if NOT "%foo%"=="%foo:bar=%" echo FOUND
Run Code Online (Sandbox Code Playgroud)

如果比较的两边不相等,则变量内必须有文本,因此删除了搜索文本.

一个小样本如何扩展该行

set foo=John goes to the bar.
if NOT "John goes to the bar."=="John goes to the ." echo FOUND
Run Code Online (Sandbox Code Playgroud)