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

时间:2010-05-05 10:43:23

标签: command-line batch-file

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

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

这些线条工作正常并将字符串“跳过椅子”更改为“跳过桌子”。现在我想用一些变量替换字符串中的“chair”一词,我不知道该怎么做。

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

有什么想法吗?

4 个答案:

答案 0 :(得分:72)

您可以使用以下小技巧:

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

call会导致另一层变量扩展,因此必须引用原始的%符号,但最终都会解决。

答案 1 :(得分:67)

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

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

答案 2 :(得分:0)

我能够使用Joey's Answer来创建函数:

用作:

@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 ENABLEDELAYEDEXPANSION”,否则这些都将无法正常工作。

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

答案 3 :(得分:-2)

这很好

"body"