I want to use the search/replace feature of the SET command in a dynamic fashion.
The normal way would be like
SET blah=double-foo
SET blah=%blah:foo=bar%
Now I want to use variables in the second line instead of foo and bar:
SET search=foo
SET repl=bar
SET blah=double-foo
ECHO %blah%
SET blah=%blah:%search%=%repl%%
ECHO %blah%
I only get
double-foo
searchrepl%
I also tried
SET blah=%blah:(%search%=%repl%)%
SET blah=%blah:(%search%)=(%repl%)%
How would I achieve this? If I do this without SET that’s fine. In the end I want the environment variable to hold double-bar.
There are two common ways (and some uncommon).
Use the double expansion by call.
In the first “scan” it expands to
CALL SET blah=%blah:foo=bar%and the call expands the seconds time to the desired result.The second way is the delayed variant
It works, because delayed expansion executes after the percent expansion.
I would prefer the delayed variant, because it’s faster and safer against special characters.
An uncommon way is the FOR-Loop-Variable variant, it works also with special characters in the search/replace variables.