Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 300
sjngm Avatar asked Mar 17 '11 09:03

sjngm


1 Answers

There are two common ways (and some uncommon).

Use the double expansion by call.

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 expands the seconds time to the desired result.

The second way is the delayed variant

SETLOCAL EnableDelayedExpansion
SET search=foo
SET repl=bar
SET blah=double-foo

SET blah=!blah:%search%=%repl%!

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.

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!"
  )
)  
like image 145
jeb Avatar answered Sep 29 '22 21:09

jeb