Reputation: 1219
Now I need get the substring form a string on batch File
I have this
set path="c:\test\branches\9.1\_build"
I need get the first value after the branches value : 9.1
But this value can be in other position like
c:\xxx\yyyy\zzzz\branches\otherbranch\zzz\uuuu\iii
In this case, I need get this: otherbranch
I need one generic solution, Thank you guys..
Upvotes: 8
Views: 29343
Reputation: 130819
Here is a simple solution that uses a handy hybrid JScript/batch utility called REPL.BAT that performs regex search and replace on stdin and writes the result to stdout. It is pure script that runs on any modern Windows machine from XP onward - no 3rd party executeable required.
It has many options, including an A
option that only lists substitued lines that match, and S
that reads from an environment variable instead of stdin. Complete documentation is embedded within the script.
Assuming REPL.BAT is in your current directory, or better yet, somewhere within your path, then the following will set value
appropriately. It will be undefined if \branches\
could not be found, or if nothing follows \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%
Upvotes: 3
Reputation: 37569
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%
Upvotes: 17
Reputation: 57252
It uses :split subroutine that can be found here 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
Upvotes: 3