11

I'm having trouble getting this batch file to do substring replacements when variables are used. Specifically when the !original! variable is specified; if it's a literal string it works fine. However, this will not do for my usage.

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

Your help is greatly appreciated.

delpium
  • 161
  • 1
  • 2
  • 7

2 Answers2

18

If you use call you can do this without the need for setlocal enabledelayedexpansion, like so:

call set str=%%str:%original%=%replacement%%%

Note: This first gets parsed to call set str=%str:chair=table%

azhrei
  • 2,303
  • 16
  • 18
4

You have got your expansion order reversed.

Normal (percent) expansion occurs at parse time (1st)
Delayed (exclamation) expansion occurs at run time (2nd)

The search and replace terms must be expanded before the search and replace can take place. So you want:

set str=!str:%original%=%replacement%!
dbenham
  • 127,446
  • 28
  • 251
  • 390
  • Thanks, that may have been an additional problem of mine. I think my problem was a lack of understanding how IF statements work in batch files. I had placed this in the THEN section of my IF statement and I believe that's why I had the results of only one variable being evaluated. This link helped me: http://stackoverflow.com/questions/4367297/how-to-substitute-variable-contents-in-dos – delpium Aug 10 '12 at 00:19