【问题标题】:Remove substring from a string从字符串中删除子字符串
【发布时间】:2019-09-08 11:54:06
【问题描述】:

如何在for 和其他循环中从字符串中删除由变量传递的子字符串(需要延迟扩展)?

我找到了%%

@echo off
setlocal enableExtensions enableDelayedExpansion
cd /D "%~dp0"
set br=^


rem br;


set "v=1!br!2!br!3"
set v=%%v:%br%=%%
echo !v!

但它似乎不起作用,如果 v 变量在迭代之间发生变化(当 %..% 需要为 !..! 时),它将不起作用。

感谢任何帮助。

【问题讨论】:

    标签: batch-file cmd


    【解决方案1】:

    您找到了%%,但显然您并未找到所有必要的信息。首先,br 必须用作!br!%br% 不起作用。其次,%%var%% 表示法将与call 一起使用(强制进行第二层解析):

    @echo off
    setlocal enableExtensions enableDelayedExpansion
    cd /D "%~dp0"
    set br=^
    
    
    rem br;
    
    set "v=1!br!2!br!3"
    call set "v=%%v:!br!=%%"
    echo !v! (also: %v%)
    

    【讨论】:

      【解决方案2】:

      您也可以在for 循环中使用echo| set /p =

      @echo off
      setlocal enableDelayedExpansion
      cd /D "%~dp0"
      set br=^
      
      
      :# Above 2 lines must be empty.
      set "v=1!br!2!br!3"
      for %%i in (!v!) do echo| set /p =%%i
      

      【讨论】:

      • 重点是删除子字符串,/br 只是一个例子
      • 删除子字符串和删除 lf/cr 是两个不同的东西。
      • [ /br | /cr/lf ] 是由 text==string 组成的字符,问题是“如何删除子字符串”
      【解决方案3】:

      这里有一些Remarks 的附加示例:

      @Echo Off
      Rem Using delayed expansion is necessary for this task.
      SetLocal EnableDelayedExpansion
      Rem The two empty lines are necessary to set br to a new line.
      Set br=^
      
      
      Rem Use the variable named br to set a variable named v to a multiline value.
      Set "v=1!br!2!br!3"
      Rem You can output all variable names beginning with v with their values using the below command.
      Set v
      Rem You can output the value for the variable named v using the below command.
      Echo !v!
      Pause
      

      如果你不能保证名为v的变量会有一个值:

      • 为了防止倒数第四行输出Environment variable v not defined,请改用Set v 2>Nul

      • 为了防止倒数第二行输出ECHO is off.,请改用Echo(!v!

      要从名为v 的现有变量中删除字符串值!br! 的所有实例,您需要使用Call 语句来引入另一个解析级别:

      Rem Expand the variable named v and substitute the string value of the variable named br with nothing.
      Call Set "v=%%v:!br!=%%"
      Rem You can output the new value for the variable named v using the below command.
      Echo(!v!
      Rem However as Delayed Expansion is no longer necessary, you could instead use.
      Echo(%v%
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-30
        • 2021-06-24
        • 2014-08-17
        相关资源
        最近更新 更多