Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do substring with variable length in a for loop inside batch files?

I am trying to do some string comparison and extraction in a batch file. The operation takes place on a set of folder names from a SVN repository.

for /f %%f in ('svn list https://dev_server/svn/product/branches') do ( 
    set folder=%%f 

    echo Folder: %folder%

    :: get substring from %folder% starting at 0 with a length of %length%
    :: if this substring is equal to %folderStart% then get substring from %folder% starting at position %length%   
)

There are a couple of problems here:

  1. The value of %%f is not assigned to %folder% for some reason.
  2. Even though I have searched the web extensively, I didn't find a solution to doing substring with variable length. The batch file substring function :~ only seems to take fixed integer values.

Does anyone have an idea how I could implement the functions in the commented section in the code above?

like image 928
user1156620 Avatar asked Jun 27 '26 00:06

user1156620


1 Answers

Dynamic substring is easy with delayed expansion.

setlocal enableDelayedExpansion
set "string=1234567890"

::using a normal variable
set len=5
echo !string:~0,%len%!

::using a FOR variable
for /l %%n in (1 1 10) do echo !string:~0,%%n!

It can also work with search and replace

like image 75
dbenham Avatar answered Jun 29 '26 15:06

dbenham