简体   繁体   中英

How to replace with percent character in cmd.exe?

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?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM