There are a few ways that are frequently used to handle the situation.
1) Look for a way to avoid the need for delayed expansion - often not possible without introducing the very slow CALL %%VAR%% syntax.
2) Toggle delayed expansion ON and OFF as needed within the loop. This is often very effective. But it can be problematic if variable values must persist. There is a limit to the number of SETLOCAL that can be used within any one CALL level, so that means ENDLOCAL must be used. But then there is the complexity of persisting a variable value accross the ENDLOCAL barrier. There are methods to do this, but they are complicated, and they slow down processing.
Just today I realized that there is a very convenient, simple, and fast solution using the hybrid JScript/batch utility - REPL.BAT
Simply use REPL.BAT within the IN() clause to escape all ^ and ! characters. Then within the DO() clause, Assign each token to a variable using something like set "var=%%A"!. The trailing ! will guarantee that ^^ will be properly converted into ^, yet the ! will not be included in the assigned value since it appears after the last quote.
Code: Select all
@echo off
setlocal enableDelayedExpansion
:: Parse the first token from a string within a variable
for /f %%A in ('repl "\^^|^!" "^^$&" s someVar') do (
set "token=%%A"!
...
)
:: Parse the first token from each line within a file
for /f %%A in ('type "someFile.txt"^|repl "\^^|^!" "^^$&"') do (
set "token=%%A"!
...
)
:: or
for /f %%A in ('repl "\^^|^!" "^^$&" <"someFile.txt"') do (
set "token=%%A"!
...
)
:: Parse the first token of each line from some command output
for /f %%A in ('someCommand^|repl "\^^|^!" "^^$&"') do (
set "token=%%A"!
...
)
This technique is so much easier and faster than any other technique I am aware of

Dave Benham