1

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?

Community
  • 1
  • 1
AplusKminus
  • 1,542
  • 1
  • 19
  • 32

1 Answers1

3

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?

Endoro
  • 37,015
  • 8
  • 50
  • 63
  • That results in `Hello!str2!World!`. Remember: I am doing this in cmd.exe not from a `.bat` file – AplusKminus Apr 29 '15 at 13:36
  • Absolute lifesaver. Would you mind commenting the example, as the `for()` is a little bit black-magic. P.S. for those who want to do it in a batch script, there is: https://stackoverflow.com/questions/2772456/string-replacement-in-batch-file. – Kenn Sebesta Jun 16 '17 at 18:45