从字符串中删除子字符串

时间:2019-04-18 07:23:00

标签: batch-file cmd

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

我找到了%%

@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变量将在迭代之间更改(当%..%需要为!..!时也将无效)。

感谢您的帮助。

3 个答案:

答案 0 :(得分: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%)

答案 1 :(得分:0)

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

@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

答案 2 :(得分:0)

这是另一个带有一些Rem方舟的例子:

@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!

要从现在存在的名为!br!的变量中删除v字符串值的所有实例,则需要使用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%