batch-file - 使用批处理根据特定值从字符串中获取部分内容

标签 batch-file batch-processing

我有以下代码:

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/

相关文章:

windows - “无法将X识别为内部或外部命令,可操作程序或批处理文件”的原因是什么?

java - cassandra pelops 在服务器上的性能比本地差

tensorflow - 使用经过训练的对象检测 API 模型和 TF 2 进行批量预测

linux - 如何在每次迭代中以批处理模式从 Linux Top 获取输出?

string - .bat 文件搜索和替换结构化文本文件中的字符串

bash - 如何重复给定的十六进制字符串

batch-file - 在脚本之间通过引用传递参数

json - 如何在 Pure Batch 中解析 JSon

javascript - 对大批量动态生成的字符串进行单元测试的方法

spring - 将数据传递给 future 的步骤 - Spring Batch