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.

2 Answers 2

19

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%

Sign up to request clarification or add additional context in comments.

Comments

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%!

1 Comment

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: stackoverflow.com/questions/4367297/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.