我有以下代码:
SET location_path=\\dc01\intern\Product\NightlyBuild\Reg\Reg_20171207.1\out\site
OR
SET location_path=\\dc01\intern\Product\Release\ex\17.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\17.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
您会注意到,要删除所需值之前的部分,您可以使用通配符 - 例如设置“trimmed=%orig:*NightlyBuild\=%”
。剥离所需值之后的部分需要更多的创造力:set trimmed=%trimmed:\out=&rem;%
。 See this page有关批处理变量字符串操作的更多信息。您还可以阅读 creating functions in batch files如果需要的话。
关于batch-file - 使用批处理根据特定值从字符串中获取部分内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48264276/