批处理中基于特定关键词批量提取字符串片段的方法咨询
嘿,这个场景我太熟了!固定长度的截取肯定搞不定这种动态路径,得用批处理里的字符串替换或者路径段遍历的方法来实现,针对你给出的两种路径格式,我给你整理了两种可行的解决方案:
方案一:用字符串替换快速定位(适合固定路径结构)
这种方法利用批处理的%变量:*关键词=%语法,直接去掉关键词之前的所有内容,再针对性剔除后面不需要的部分,代码简洁高效:
@echo off setlocal enabledelayedexpansion REM 替换成你的目标路径 SET "location_path=\\dc01\intern\Product\NightlyBuild\Reg\Reg_20171207.1\out\site" REM SET "location_path=\\dc01\intern\Product\Release\ex\17.12\site" SET "location_path_trimmed=" REM 检查路径是否包含NightlyBuild echo !location_path! | findstr /i "NightlyBuild" >nul if not errorlevel 1 ( REM 去掉NightlyBuild及之前的所有内容 SET "temp=!location_path:*NightlyBuild\=!" REM 去掉out\site及之后的内容,得到目标片段 SET "location_path_trimmed=!temp:\out\site=!" ) else ( REM 检查路径是否包含Release echo !location_path! | findstr /i "Release" >nul if not errorlevel 1 ( REM 去掉Release及之前的所有内容 SET "temp=!location_path:*Release\=!" REM 拆分出ex之后的部分,再去掉site及之后的内容 SET "temp1=!temp:\=" & SET "temp2=!" SET "location_path_trimmed=!temp2:\site=!" ) ) echo location_path_trimmed = !location_path_trimmed! pause endlocal
代码说明:
%变量:*关键词=%:这个语法会把变量中关键词及之前的所有字符替换为空,直接得到关键词后面的内容- 针对两种路径的不同结构,分别处理后续的截取逻辑:NightlyBuild后需要保留到
\out\site之前的部分;Release后需要提取ex之后、\site之前的片段
方案二:遍历路径段提取(更灵活)
如果你的路径结构可能有小变动,这种遍历每个路径段的方法更可靠,通过定位关键词后计数提取目标段:
@echo off setlocal enabledelayedexpansion REM 替换成你的目标路径 SET "location_path=\\dc01\intern\Product\NightlyBuild\Reg\Reg_20171207.1\out\site" REM SET "location_path=\\dc01\intern\Product\Release\ex\17.12\site" SET "location_path_trimmed=" SET "found_keyword=" SET "count=0" REM 把路径中的\替换为" ",方便遍历每个路径段 SET "path_segments=!location_path:\=" "!" for %%a in (!path_segments!) do ( if defined found_keyword ( REM 找到NightlyBuild后,取后续2个段并拼接 if /i "!found_keyword!"=="NightlyBuild" ( if !count! equ 0 ( SET "location_path_trimmed=%%a" SET /a count+=1 ) else if !count! equ 1 ( SET "location_path_trimmed=!location_path_trimmed!\%%a" goto :extract_done ) ) REM 找到Release后,取后续第2个段 if /i "!found_keyword!"=="Release" ( if !count! equ 1 ( SET "location_path_trimmed=%%a" goto :extract_done ) SET /a count+=1 ) ) else ( REM 判断当前段是否是目标关键词 if /i "%%a"=="NightlyBuild" ( SET "found_keyword=NightlyBuild" SET "count=0" ) else if /i "%%a"=="Release" ( SET "found_keyword=Release" SET "count=0" ) ) ) :extract_done echo location_path_trimmed = !location_path_trimmed! pause endlocal
代码说明:
- 先把路径中的
\替换为空格,让for循环可以逐个遍历每个路径段 - 遍历过程中定位到
NightlyBuild或Release后,通过计数器count来提取对应的后续段:- NightlyBuild后取第1、2个段(
Reg和Reg_20171207.1)并拼接 - Release后取第2个段(跳过
ex,取17.12)
- NightlyBuild后取第1、2个段(
两种方案都能完美适配你给出的两种路径场景,你可以根据自己的实际需求选择~
内容的提问来源于stack exchange,提问作者Rotan075




