Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
998 views
in Technique[技术] by (71.8m points)

windows - Find out whether an environment variable contains a substring

I need to find out if a certain environment variable (let's say Foo) contains a substring (let's say BAR) in a windows batch file. Is there any way to do this using only batch file commands and/or programs/commands installed by default with windows?

For example:

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

What should the marked line above be to make this simple batch file print "Found BAR"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Of course, just use good old findstr:

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

Instead of echoing you can also branch elsewhere there, but I think if you need multiple statements based on that the following is easier:

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

Edit: Take note of jeb's solution as well which is more succinct, although it needs an additional mental step to figure out what it does when reading.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...