Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"?

like image 534
LCC Avatar asked Mar 30 '11 19:03

LCC


People also ask

How do you check if a variable contains a substring in bash?

To check if a string contains a substring in Bash, use comparison operator == with the substring surrounded by * wildcards.

How do I see my environment variables?

On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables.


2 Answers

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.

like image 146
Joey Avatar answered Sep 27 '22 18:09

Joey


The findstr solution works, it's a little bit slow and in my opinion with findstr you break a butterfly on a wheel.

A simple string replace should also work

if "%foo%"=="%foo:bar=%" (
    echo Not Found
) ELSE (
    echo found
)

Or with inverse logic

if NOT "%foo%"=="%foo:bar=%" echo FOUND

If both sides of the comparision are not equal, then there must be the text inside the variable, so the search text is removed.

A small sample how the line will be expanded

set foo=John goes to the bar.
if NOT "John goes to the bar."=="John goes to the ." echo FOUND
like image 25
jeb Avatar answered Sep 27 '22 19:09

jeb