Windows: How to use a "set" with dynamic search and replace?

I want to use the search / replace function of the SET command dynamically.

The usual way would be like

 SET blah=double-foo SET blah=%blah:foo=bar% 

Now I want to use the 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 can i achieve this? If I do this without SET , that's fine. In the end, I want the environment variable to hold a double-bar .

+7
source share
1 answer

There are two common ways (and some unusual ones).

Use double call extension.

 SET search=foo SET repl=bar SET blah=double-foo CALL SET blah=%%blah:%search%=%repl%%% 

In the first β€œscan”, it expands to CALL SET blah=%blah:foo=bar% , and the call increases the time in seconds to the desired result.

The second way is a delayed option.

 SETLOCAL EnableDelayedExpansion SET search=foo SET repl=bar SET blah=double-foo SET blah=!blah:%search%=%repl%! 

This works because slow expansion is performed after the percentage increase.

I would prefer a delayed option because it is faster and safer against special characters.

The FOR-Loop-Variable option is an unusual way; it also works with special characters in search / replace variables.

 SETLOCAL EnableDelayedExpansion SET "search=foo>" SET "repl=bar & bar" SET "blah=double-foo> &|<>" for %%s in ("!search!") do ( for %%r in ("!repl!") do ( SET "blah=!blah:%%~s=%%~r!" ) ) 
+7
source

All Articles