Replacing a batch file substring using variables

I am having trouble getting this batch file to replace a substring when using variables. In particular, when! Original! a variable is specified; if it is a literal string, it works fine. However, this will not be done for my use.

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

Your help is greatly appreciated.

+8
variables substring replace batch-file
source share
2 answers

If you use call , you can do this without having to setlocal enabledelayedexpansion , for example:

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

Note. First it is parsed for call set str=%str:chair=table%

+13
source share

You have canceled the extension order.

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

Search and replace conditions should be expanded before search and replace can take place. So you want:

 set str=!str:%original%=%replacement%! 
+3
source share

All Articles