批处理文件中的字符串替换

我们可以使用以下命令替换批处理文件中的字符串

set str="jump over the chair"
set str=%str:chair=table%

These lines work fine and change the string "jump over the chair" to "jump over the table". Now I want to replace the word "chair" in the string with some variable and I don't know how to do it.

set word=table
set str="jump over the chair"
??

有什么想法吗?

248301 次浏览

您可以使用! ,但必须设置 ENABLEDELAYEDEXPANsion 开关。

setlocal ENABLEDELAYEDEXPANSION
set word=table
set str="jump over the chair"
set str=%str:chair=!word!%

你可以使用以下小技巧:

set word=table
set str="jump over the chair"
call set str=%%str:chair=%word%%%
echo %str%

那里的 call导致另一个层的变量扩展,使它必须引用原来的 %的迹象,但它所有的工作在最后。

This works fine

@echo off
set word=table
set str=jump over the chair
set rpl=%str:chair=%%word%
echo %rpl%

我用乔伊的答案创建了一个函数:

使用它作为:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION


SET "MYTEXT=jump over the chair"
echo !MYTEXT!
call:ReplaceText "!MYTEXT!" chair table RESULT
echo !RESULT!


GOTO:EOF

这些函数放在批处理文件的底部。

:FUNCTIONS
@REM FUNCTIONS AREA
GOTO:EOF
EXIT /B


:ReplaceText
::Replace Text In String
::USE:
:: CALL:ReplaceText "!OrginalText!" OldWordToReplace NewWordToUse  Result
::Example
::SET "MYTEXT=jump over the chair"
::  echo !MYTEXT!
::  call:ReplaceText "!MYTEXT!" chair table RESULT
::  echo !RESULT!
::
:: Remember to use the "! on the input text, but NOT on the Output text.
:: The Following is Wrong: "!MYTEXT!" !chair! !table! !RESULT!
:: ^^Because it has a ! around the chair table and RESULT
:: Remember to add quotes "" around the MYTEXT Variable when calling.
:: If you don't add quotes, it won't treat it as a single string
::
set "OrginalText=%~1"
set "OldWord=%~2"
set "NewWord=%~3"
call set OrginalText=%%OrginalText:!OldWord!=!NewWord!%%
SET %4=!OrginalText!
GOTO:EOF

记住你必须在批处理文件的顶部添加“ SETLOCAL ENABLEDELAYDEXPANION”,否则这些都不能正常工作。

SETLOCAL ENABLEDELAYEDEXPANSION
@REM # Remember to add this to the top of your batch file.