Windows Batch check if variable starts with, ends with and contains a specific string

后端 未结 3 814
天涯浪人
天涯浪人 2020-12-17 22:17

I\'m trying to check if a variable in a batch file starts with \" contains BETA somewhere and ends with \").

Is it possible? A

3条回答
  •  不知归路
    2020-12-17 23:19

    @ECHO OFF
    SETLOCAL
    SET var=abc&CALL :check
    SET var="abc"&CALL :llcheck
    SET var="")&CALL :check
    SET var=")"&CALL :llcheck
    SET var=abc")"&CALL :llcheck
    SET var=xyzbetazyx&CALL :check
    SET var="xyzbetazyx"&CALL :llcheck
    SET var=xyzbetazyx")"&CALL :llcheck
    SET var=xyzbetazyx")"&CALL :check
    SET var="xyzbetazyx")&CALL :check
    GOTO :eof
    :: Lop last, then check
    :llcheck
    SET var=%var:~0,-1%
    :check
    SET result=N
    SET var2=%var%
    SET varvar=%var%
    
    >test1.txt ECHO %var:~0,1%%var:~-2%
    >test2.txt ECHO "")
    FC test1.txt test2.txt >nul
    IF ERRORLEVEL 1 GOTO done
    SET var|FINDSTR /b "var="|FINDSTR /i "beta" >nul
    IF ERRORLEVEL 1 GOTO done
    SET result=Y
    :done
    ECHO %var% starts " has BETA and ends ") : %result% 
    GOTO :eof
    

    Where there's a will...

    Setting variables with unbalanced " can be tricky. I just set it up balanced and lopped off the last character (:llcheck entry : lop last and check.

    Essentiall, I've copied the variable into var2 and varvar in oder to demo what happens should these variablenames be set.

    Two files are then generated. TEST1.TXT contains the first and last 2 character of var and TEST2.TXT simply "")

    Compare the two - if they're not identical, then the variable does NOT start " and end ") Otherwise well - could simply have written var out to a file and used findstr to find beta, but I decided to send the output of SET var which should be the contents of ALL of the var* variables in the form

    var=abc
    var2=abc
    varvar=abc
    

    into findstr, finding the one that starts (/b) var= and finding whether THAT contains the string beta The /i selects case-insensitive. If you want specifically BETA in UPPER-CASE, simply change beta to BETA and remove the /i.

    result is set to Y or N

提交回复
热议问题