Batch file if string starts by

萝らか妹 提交于 2020-08-08 03:36:41

问题


I need to know if a string starts by something, produced this little example to explain (I'm using a Batch compiler/Pre-processor or whatever with advanced commands) :

rem GetInput
if "%result%"=="cd *" goto Cd
:Cd
if "%result%"=="cd meow" Echo Going to directory 'meow'...

But this code doesn't work, at the line with a "cd *" the script dont go to :Cd if the string %result% starts with the letters cd.

Thank you


回答1:


If I understand this correctly, you're trying to determine whether that value for %result% begins with 'cd', and you're unsuccessfully using a * as a wildcard to determine this.

There are a few different ways to handle this. Here's one way: You can check to see if the first two characters are equal to 'cd':

if /i "%result:~0,2%"=="cd" goto Cd

set /? has more on this.




回答2:


here's a comparatively robust and universal startsWith subroutine (with two examples).It sets errorlevel to 1 if the strings starts with an another string and to 0 if does not.

@echo off
set string1=abc123123
set checker1=abc

call :startsWith %string1% %checker1%
if %errorlevel% equ 1 (
    echo %string1% starts with %checker1%
) else (
    echo %string1% does NOT start with %checker1%
)

set string2=xyz123123 abc

call :startsWith %string2% %checker2%
if %errorlevel% equ 1 (
    echo %string2% starts with %checker2%
) else (
    echo %string2% does NOT start with %checker2%
)




exit /b 0

::::::::::::::::::::::::::::::::::::::::
:::----- subroutine starts here ----::::
:startsWith [%1 - string to be checked;%2 - string for checking ] 
@echo off
rem :: sets errorlevel to 1 if %1 starts with %2 else sets errorlevel to 0

setlocal EnableDelayedExpansion

set "string=%~1"
set "checker=%~2"
rem set "var=!string:%~2=&echo.!"
set LF=^


rem ** Two empty lines are required
rem echo off
for %%L in ("!LF!") DO (
    for /f "delims=" %%R in ("!checker!") do ( 
        rem set "var=!string:%%~R%%~R=%%~L!"
        set "var=!string:%%~R=#%%L!"
    )
)
for /f "delims=" %%P in (""!var!"") DO (
    if "%%~P" EQU "#" (
        endlocal & exit /b 1
    ) else (
        endlocal & exit /b 0
    )
)
::::::::::::::::::::::::::::::::::::::::::::::::::


来源:https://stackoverflow.com/questions/36228474/batch-file-if-string-starts-by

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!