Reputation: 34909
How can I, with delayed expansion enabled, escape the exclamation mark inside of a command that is stated as an argument of a FOR /F command, like
set FOO=BAR
setlocal enabledelayedexpansion
rem non-quoted variable
for /F %L in ('echo !FOO!') do echo %L
endlocal
or
set FOO=BAR
setlocal enabledelayedexpansion
rem quoted variable
for /F %L in ('echo "!FOO!"') do echo %L
endlocal
to get BAR
or "BAR"
returned, respectively?
Unfortunately it is expanded to !FOO!
or "!FOO!"
.
When using immediate expansion (meaning %FOO%
or "%FOO%"
) I get what I want.
I tried to use ^!
, ^^!
, !!
,..., also together with the "usebackq" option (`echo`
), but no success.
Even preceding the first echo
with a call
command does not succeed.
Can you please help me?
Upvotes: 0
Views: 473
Reputation: 70923
From the syntax used (%L
) you are running it in the command line, and from this context the command setlocal enabledelayedexpansion
has no effect. If you read setlocal /?
you will see this command is for batch files.
So, the real problem is that !FOO!
is parsed as a literal as delayed expansion is not active (the default cmd
configuration).
How to do it from command line? Enabling the delayed expansion for the cmd
instance
set "FOO=bar"
cmd /v /c"for /F %L in ('echo !FOO!') do echo %L"
Note that the expansion of the !FOO!
variable is done inside the cmd /v /c
instance, not inside the cmd
instance started to execute the echo
command.
Upvotes: 4