Batch file substring replacement using variables
10,074
Solution 1
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%
Solution 2
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%!
Author by
delpium
Updated on July 23, 2022Comments
-
delpium almost 2 years
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 over 11 yearsThanks, 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: stackoverflow.com/questions/4367297/…