How to replace with percent character in cmd.exe?

狂风中的少年 提交于 2019-12-23 03:51:36

问题


In the Windows command prompt, I am trying to replace the space in set string=Hello World with the string %20. Naively trying to use the string literal %20 like this:

set string=%string: =%20%

results in HelloWorld20%. Trying to use the escape character ^ like this:

set string=%string: =^%20%

also results in HelloWorld20%. Trying to escape the % by doubling it like this:

set string=%string: =%%20%

results in HelloWorld%20%. I also tried to use another variable to do the replacement like this:

set r=%20
set string=%string: =%r%%

which results in HelloWorldr%%.

I found this, which handles the escaping of percent characters in variables. I also found this, which handles the escaped input of percent characters. But neither one seems to apply to string replacing.

A tutorial/docu page for the Windows cmd.exe which I found online tells me I have the correct syntax, but does not cover replacing with percent characters.

After reading all of those, I tried:

setlocal EnableDelayedExpansion
set string=!string: =%20!

which results in !string: =%20!.

I am out of ideas, can you help?


回答1:


You need delayed expansion in this case:

set "str1=Hello World!"
set "str2=%20"
for /f "delims=" %a in ('cmd /v:on /c @echo "%str1: =!str2!%"') do set "str3=%~a"
echo %str3%

What is delayed expansion?



来源:https://stackoverflow.com/questions/29944902/how-to-replace-with-percent-character-in-cmd-exe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!