Find out whether an environment variable contains a substring

后端 未结 4 1871
盖世英雄少女心
盖世英雄少女心 2020-12-16 14:21

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

4条回答
  •  有刺的猬
    2020-12-16 14:40

    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.

提交回复
热议问题