如何在批处理文件中的for循环中使用可变长度的子字符串?

问题描述 投票:7回答:2

我试图在批处理文件中进行一些字符串比较和提取。该操作在SVN存储库的一组文件夹名称上进行。

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%   
)

这里有几个问题:

  1. 由于某种原因,%% f的值未分配给%folder%。
  2. 即使我在网上广泛搜索,我也没有找到一个解决方案来做可变长度的子字符串。批处理文件substring函数:〜似乎只取固定的整数值。

有没有人知道如何在上面的代码中的注释部分实现这些功能?

windows batch-file substring
2个回答
6
投票

动态子串很容易延迟扩展。

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!

它也可以用于搜索和替换


0
投票

你的路线

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
© www.soinside.com 2019 - 2024. All rights reserved.