The extension order is critical when performing a search and replace operation using a variable to search and / or replace. The internal variable must be expanded before the start of the external search and replacement. Trying to use a delayed extension for both obviously cannot work, because the delayed extension occurs at one point in time.
The classic method of expanding a variable inside another variable uses a delayed extension for the external and normal for the internal: echo !var1:SomeText=%var2%!"
I'm going to suggest that you wanted to use a deferred extension for some reason. Perhaps the extension takes place inside a block of code, and one of the variables was set in the same block. A normal extension will not work because it cannot see the value that was assigned in the block until the block completes.
Solution 1
One way to solve the problem is to use CALL:
call echo %%var1:SomeText=!var2!%%
This works as follows:
The percentage phase of the analyzer converts two percent to one percent, resulting in
call echo %var1:SomeText=!var2!%
Extension delay is expanding! var2 !, resulting in
call echo %var1:SomeText=ReplacementText%
CALL ECHO is performed and an additional level of percentage processing is performed. Search and replace are performed, resulting in the display of ResultOfSearchAndReplace .
It works, but it is relatively slow. It may also have problems if the extended value has special characters such as > , & or | . I rarely use this technique.
Decision 2
A quick and reliable method is to do the expansion in two steps. First pass the value !var2! into the FOR variable. Then you can use the FOR variable as a replacement string and use the slow extension for the second step. This completely eliminates the more fragile increase in interest.
for /f "delims=" %%A in ("!var2!") do echo !var1:SomeText=%%A!
The above works because the variable expansion of the FOR variable occurs before the deferred extension.
This is by far my preferred method for attacking this issue.
For a more detailed explanation of the various phases of the parser analyzer, see jeb's answer to How is the Windows Command Interpreter Script Interpreter (CMD.EXE)?
source share