现在我需要在批处理文件
上获取子字符串形式的字符串我有这个
set path="c:\test\branches\9.1\_build"
我需要在分支值后得到第一个值:9.1
但是这个值可以处于其他位置,如
c:\xxx\yyyy\zzzz\branches\otherbranch\zzz\uuuu\iii
在这种情况下,我需要这样:otherbranch
我需要一个通用解决方案,谢谢你们..
答案 0 :(得分:17)
set "mypath=c:\test\branches\9.1\_build"
set "value=%mypath:*\branches\=%"
if "%value%"=="%mypath%" echo "\branches\" not found &goto :eof
for /f "delims=\" %%a in ("%value%") do set "value=%%~a"
echo %value%
答案 1 :(得分:3)
它使用:可在此处找到的拆分子例程http://ss64.org/viewtopic.php?id=1687
@echo off
setlocal
rem not good idea to overwrite path
set "_path="c:\test\branches\9.1\_build""
call :split %_path% branches 2 part
call :split %part% \ 2 part2
echo %part2%
endlocal
goto :eof
:split [%1 - string to be splitted;%2 - split by;%3 - possition to get; %4 - if defined will store the result in variable with same name]
setlocal EnableDelayedExpansion
set "string=%~1"
set "splitter=%~2"
set /a position=%~3-1
set LF=^
rem ** Two empty lines are required
echo off
for %%L in ("!LF!") DO (
for /f "delims=" %%R in ("!splitter!") do (
set "var=!string:%%R=%%L!"
if "!var!" EQU "!string!" (
echo "!string!" does not contain "!splitter!" >2
exit /B 1
)
)
)
if !position! equ 0 ( set "_skip=" ) else (set "_skip=skip=%position%")
for /f "%_skip% delims=" %%P in (""!var!"") DO (
set "part=%%~P"
goto :end_for
)
:end_for
if "!part!" equ "" echo Index Out Of Bound >2 &exit /B 2
endlocal & if "%~4" NEQ "" (set %~4=%part%) else echo %part%
exit /b 0
答案 2 :(得分:3)
这是一个简单的解决方案,它使用方便的hybrid JScript/batch utility called REPL.BAT执行正则表达式搜索并替换stdin并将结果写入stdout。它是从XP开始在任何现代Windows机器上运行的纯脚本 - 不需要第三方可执行。
它有很多选项,包括A
选项,只列出匹配的替换行,以及S
从环境变量而不是stdin读取。完整的文档嵌入在脚本中。
假设REPL.BAT位于当前目录中,或者更好,位于路径中的某个位置,则以下内容将适当地设置value
。如果无法找到\branches\
,或者\branches\
后面没有任何内容,则不会定义:
set "mypath=c:\test\branches\9.1\_build"
set "value="
for /f "eol=\ delims=" %%A in (
'repl.bat ".*\\branches\\([^\\]*).*" "$1" AS mypath'
) do set "value=%%A"
echo %value%