Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch, replace a delay expansion string with delay expansion parameters

basically I am just using this piece to replace a string in my var, but I can't get nested delay expansion to work correctly. Is this even possible?

set replace=!replace:!search!=!replaceVal!!

I know what going on when it is getting executed. It stops at after the first complete set which would be set replace=!replace:! and then it attempts to execute the last part, but is there a way to escape them so it will properly get my outcome?

like image 666
Matthew Avatar asked Mar 10 '23 05:03

Matthew


1 Answers

I think the most secure way is the following:

for /F "delims=" %%S in (^""!search!"^") do (
    for /F "delims=" %%R in (^""!replaceVal!"^") do (
        set "replace=!replace:%%~S=%%~R!"
    )
)

So the only remaining restrictions are those that apply for the sub-string replacement syntax anyway.


An even simpler yet equally safe approach is this:

for /F "delims=" %%S in (^""!search!=!replaceVal!"^") do (
    set "replace=!replace:%%~S!"
)

As you can see there is even no need to keep search and replace strings separated until the end.

like image 191
aschipfl Avatar answered Apr 05 '23 22:04

aschipfl