How to make variable-length substring in for loop inside batch files?

I am trying to perform string comparison and extraction in a batch file. The operation is performed by a set of folder names from the 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 several issues here:

  • The value %% f is not assigned to% folder% for any reason.
  • Despite the fact that I searched on the Internet many times, I did not find a solution for a variable-length substring. Batch file substring function: ~ only seems to accept fixed integer values.

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

+5
source share
2 answers

Dynamic substring is simple 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

+4

echo %folder% 

echo !folder! 

,

@echo off
    setlocal ENABLEDELAYEDEXPANSION

    set theString=abcd

    for %%f in (1 2 3 4) do ( 

        set pos=%%f

        call :Resolve theString:~0,!pos!

        echo !retval!

    )

goto :eof

:Resolve

  for  %%a in ("^!%*^!") do set retval=%%~a

goto :eof

a
ab
abc
abcd
0

All Articles