开发者

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%=%re开发者_运维问答pl%%
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.

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!"
  )
)  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜