2

我正在尝试批量制作一个 sub 在字符串中找到一个字符串并将其替换为第三个。环顾四周,我发现在这里SET我可以用命令擦除一个字符串。

所以,这就是我尝试过的:

:modifyString what with [in]
SET _what=%~1
ECHO "%_what%"
SET "_with=%~2
ECHO "%toWith%"
SET _In=%~3
ECHO "%_In%"
SET _In=%_In:%toWhat%=%toWith%%
ECHO %_In%
SET "%~3=%_In%"
EXIT /B

ECHOs 仅用于“调试”目的。

我所知道的是错误在...

SET _In=%_In:%toWhat%=%toWith%%

...因为关闭%_in%变量的 % 字符。

我也尝试过诸如...

SET _In=%_In:!toWhat!=!toWith!%
SET _In=!_In:%toWhat%=%toWith%!

...以及其他毫无意义的人。

这是主要问题,另一个是返回%_In%[in]

有小费吗?

4

2 回答 2

4

这是一个使用!DelayedExpansion 方法的示例。

@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "xxString=All your base are belong to us"
set "xxSubString=your base are belong"
set "xxNewSubString=of your bases belong"
echo Before
set xx
echo.
set "xxString=!xxString:%xxSubString%=%xxNewSubString%!"
echo After
set xx
endlocal
pause >nul

输出

Before
xxNewSubString=of your bases belong
xxString=All your base are belong to us
xxSubString=your base are belong

After
xxNewSubString=of your bases belong
xxString=All of your bases belong to us
xxSubString=your base are belong

固定你的

@echo off
:: Make sure that you have delayed expansion enabled.
setlocal EnableDelayedExpansion

:modifyString what with [in]
SET "_what=%~1"
SET "_with=%~2"
SET "_In=%~3"
ECHO "%_what%"
ECHO "%_with%"
ECHO "%_In%"
:: The variable names were not the same as the ones
:: defined above.
SET _In=!_In:%_what%=%_with%!
ECHO %_In%

:: This will not change the value of the 3rd parameter
:: but instead will create a new parameter with the
:: value of %3 as the variable name.
SET "%~3=%_In%"
endlocal
EXIT /B

如何在不延迟扩展的情况下进行子字符串替换。使用该call命令创建两个级别的变量扩展。使用单%环绕变量首先展开,然后使用双%%环绕变量展开第二次。

@echo off
setlocal EnableExtensions
set "xxString=All your base are belong to us"
set "xxSubString=your base are belong"
set "xxNewSubString=of your bases belong"
echo Before
set xx
echo.
call set "xxString=%%xxString:%xxSubString%=%xxNewSubString%%%"
echo After
set xx
endlocal
pause >nul
于 2013-02-02T14:54:36.943 回答
2

谢谢大家!

我把我最后做的东西贴给你:

:modifyString what with in tRtn
set "_in=%~3"
set "_in=!_in:%~1=%~2!"
IF NOT "%~4" == "" SET %~4=%_in%
EXIT /B

EG 如果我以这种方式调用这个子:

SET "str=All your base are belong to us"
SET "toFind=your base are belong"
SET "space=of your bases belong"
ECHO %str%
CALL :modifyString "%toFind%" "%space%" "%str%" string

%string% 将成为新的更正字符串,所以如果你这样做......

ECHO "%string%"

它会打印:

"All of your bases belong to us"

PS如果我迟到了,我很抱歉,但由于我的声誉很低,我不得不等待!

于 2013-02-02T23:17:34.287 回答