for .... do (
call echo !line:%%foo%%=bar!
)
The code I used in the bat file intended to replace the variable %foo%
value to bar.
%foo%
as literal %
sign. The same result as command echo !line:%%foo%%=bar!
(withtout call) does. The call
command does not work.
I wonder why it can't wor开发者_运维技巧k as call echo %%foo%%
so that call echo
would parse %foo%
value after reading the command line from bat file.It can't work because of the order of the parser phases.
Sample execution for
set foo=xxx
set line=Content xxx # %%foo%% #
The first phase is the percent expansion phase.
That you used it in a parenthesis block doesn't change this behaviour.
So you get
call echo !line:%foo%=bar!
Then the execution of the block begins, and if the line is executed the next relevant phase is the delayed expansion phase, the %foo%
will be replaced not the content, so you get
call echo Content xxx # bar #
Now the call restarts the parser with the percent expansion, but there aren't percents anymore.
I suppose the content of foo
can change inside of your FOR-Loop, so you need to expand it anytime, not only once while parsing the block.
And even if you escape the exclamation marks, so that they are enabled first after the call, it can't work, as delayed expansion doesn't work inside of a call-execution.
But you can use this instead, this works as the FOR-Variable expansion phase is just before the delayed expansion phase.
for ... do (
for /F "delims=" %%F in("!foo!") DO
echo !line:%%F=bar!
)
Some explanations about the parser phases are at How does the Windows Command Interpreter (CMD.EXE) parse scripts?
精彩评论