根据批处理的特定值从字符串中获取部分

Get part out of string based on a specific value with batch

我有以下代码:

SET location_path=\dc01\intern\Product\NightlyBuild\Reg\Reg_20171207.1\out\site
OR
SET location_path=\dc01\intern\Product\Release\ex.12\site

现在我想从变量中获取以下值:

location_path_trimmed = Reg\Reg_20171207.1
OR
location_path_trimmed = 17.12

因此,对于每个路径,应该从变量中取出不同的部分。因此,例如,我需要一种搜索​​单词的方法:“NightlyBuild”或“Release”以检索所需的值。我尝试通过使用左字符串方法来做到这一点,例如:

%location_path:~0,4%

但这不起作用。谁能指导我正确的方向?

您可以使用 echo %str% | find /i "Release" 来测试 Release 等。然后您可以使用 for /F 循环来标记路径值中以 / 作为分隔符的部分。或者,如果您需要剥离的组件可能处于不可预测的标记位置,您可以改为使用可变子字符串替换来剥离您需要的部分。

下面是一个演示子字符串替换方法的示例:

@echo off & setlocal

SET "location_path=\dc01\intern\Product\NightlyBuild\Reg\Reg_20171207.1\out\site"
call :trim "%location_path%" trimmed || exit /b 1
set trimmed

SET "location_path=\dc01\intern\Product\Release\ex.12\site"
call :trim "%location_path%" trimmed || exit /b 1
set trimmed

goto :EOF

:trim <path> <return_var>
setlocal disabledelayedexpansion
set "orig=%~1"
echo(%~1 | find /i "NightlyBuild\" >NUL && (
    set "trimmed=%orig:*NightlyBuild\=%"
) || (
    echo(%~1 | find /i "Release\" >NUL && (
        set "trimmed=%orig:*ex\=%"
    ) || (
        endlocal
        >&2 echo Error: %~1 contains unexpected build info
        exit /b 1
    )
)

set trimmed=%trimmed:\out=&rem;%
set trimmed=%trimmed:\site=&rem;%
endlocal & set "%~2=%trimmed%" & goto :EOF

您会注意到,要去除所需值之前的部分,您可以使用通配符——例如set "trimmed=%orig:*NightlyBuild\=%"。在 之后剥离部分 您想要的值需要更多的创造力:set trimmed=%trimmed:\out=&rem;%See this page for more information on batch variable string manipulation. You can also read about creating functions in batch files 如果需要的话。

您甚至可以这样做:

@Echo Off
Set "location_path=\dc01\intern\Product\NightlyBuild\Reg\Reg_20171207.1\out\site"
Rem Set "location_path=\dc01\intern\Product\Release\ex.12\site"

If /I "%location_path:\NightlyBuild\=%"=="%location_path%" (
    If /I Not "%location_path:\Release\=%"=="%location_path%" (
        Set "location_path_trimmed=%location_path:*\Release\=%")) Else (
    Set "location_path_trimmed=%location_path:*\NightlyBuild\=%")
Set "location_path_trimmed=%location_path_trimmed:*\=%"
Set "location_path_trimmed=%location_path_trimmed:\="&:"%"

Set location_path_trimmed 2>Nul
Pause

出于测试目的,只需根据需要在行 23 之间切换 Rem方舟。