How to extract a substring in a batch file

Now I need to get a substring as a string in a batch file

I have it

set path="c:\test\branches\9.1\_build" 

I need to get the first value after the branch value: 9.1

But this value may be in a different position, for example

 c:\xxx\yyyy\zzzz\branches\otherbranch\zzz\uuuu\iii 

In this case, I need to get the following: otherbranch I need one general solution, thanks guys ..

+7
substring batch-file
source share
3 answers
 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% 
+16
source share

It uses: split routine, which 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 
+3
source share

Here is a simple solution that uses the convenient hybrid JScript / batch utility REPL.BAT , which searches for and replaces regular expressions with stdin and writes the result to stdout. This is a clean script that runs on any modern Windows machine with XP and beyond - no third-party executable file is required.

It has many options, including option A , which displays only matching strings, and S , which are read from the environment variable instead of stdin. Full documentation is built into the script.

Assuming REPL.BAT is in your current directory or, even better, somewhere inside your path, the following sets the value accordingly. It will be undefined if \branches\ cannot 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% 
+3
source share

All Articles