Command line 批处理文件中的字符串替换
我们可以使用以下命令替换批处理文件中的字符串Command line 批处理文件中的字符串替换,command-line,batch-file,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" ?? 有什么想法吗?你可以用!,但必须设置ENABLEDELAYEDEXPANSION开关 setlocal ENAB
set str="jump over the chair"
set str=%str:chair=table%
这些行很好地工作,并将字符串“跳过椅子”更改为“跳过桌子”。现在我想用一些变量替换字符串中的单词“chair”,但我不知道怎么做
set word=table
set str="jump over the chair"
??
有什么想法吗?你可以用!,但必须设置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%
那里的调用
会导致另一层变量扩展,因此有必要引用原始的%
符号,但最终一切都会解决。这很好
@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 ENABLEDELAYEDEXPANSION”添加到批处理文件的顶部,否则这些都无法正常工作
SETLOCAL ENABLEDELAYEDEXPANSION
@REM # Remember to add this to the top of your batch file.
我喜欢这个解决方案,在批处理文件中转义字符串总是有问题的,ENABLEDELAYEDEXPANSION只是增加了另一个需要担心的字符。关于Joey提供的答案很重要。您需要将代码放入批处理文件以使其工作。如果您只是在命令行中测试它,它将在“word%%%%上返回意外的
%”跳转。请注意,批处理文件中的代码和命令行中的代码可能会产生不同的结果。基于dadhi的即时评论,命令行的解决方案如下:。向上投票此答案,因为它是双向的,环境变量位于任意位置,或同时位于“before”和“after”位置位置:set-word=table
set-str=“跳过椅子”
调用set-str=%%%str:chair=%word%%
echo%str%
set-word1=chairset-word2=deskset-str=“跳过椅子”调用集str=%%str:%word1%=%word2%%
echo%str%'
将“本地路径”转换为“管理员共享”路径非常有用,方法是在\\servername\前面加上前缀,然后使用此技巧将驱动器号冒号替换为$。可能的副本有更非正式的答案(它的解决方案与这里的答案相同)现在谁是第一个并不重要,但最好将相同的问题联系起来,并指出最不可反驳的答案。但是如果str
本身是延迟扩展造成的呢?set str=!str:chair=!word!!
无法正常工作。我得到“跳过!word!”
@ImaginaryHuman072889我可以使用这个和下面的答案的组合,即,调用集str=%%%str:chair=!word!%%
对不起,它看起来不错,但它是错的!它删除了chair
这个词,并附加了table
,但不交换这两个词。尝试用替换over
这个词呃
然后你得到跳到椅子下面