I currently don't have access to a Windows machine at the moment, so I can't test or verify. But I think I see a couple problems with aGerman's code.
1) The last quote must be escaped, else the closing parenthesis is treated as a string literal. I don't think that code will run at all.
My mistake. The code should run just fine because the preceding %\n% escapes the end of the line, which is stripped, and then the next character is also escaped, which happens to be the quote.
2) The commas should not require escaping, unless you are worried about the
XP FOR /F bug. If you do want the code to be safe on XP, then all token delimiters must be escaped. In this case that would be commas and spaces. Disregarding the XP bug, FOR /F should not require token delimiters to be escaped or quoted. It is only the simple FOR command that uses token delimiters as the iteration delimiter.
If I were to write aGerman's code, I would use USEBACKQ and substitute ' for " so that I don't have to worry about escaping the quotes.
I generally only use the FOR /F <LF> multi line string trick if I have a delimited string that I want to iterate, in which case I would use expansion find/replace to substitute <LF> for the delimiter, all within the IN() clause.
For example (again, untested):
Code: Select all
@echo off
setlocal
set "str=1,Martini Shaker|2,Wine Bottle|3,Beer Glass"
(set LF=^
%= This creates a Line Feed (0x0A) character - DO NOT ALTER =%
)
setlocal enableDelayedExpansion
for %%L in ("!LF!") do for /f "tokens=1,2 delims=," %%A in ("!str:|=%%~L!") do (
if "!!" == "" endlocal %= pop SETLOCAL stack only if delayed expansion is enabled to preserve any ! that may be in the strings =%
echo T1=%%A T2=%%B
)
If I want to iterate a series of string literals embedded within my source code, then I generally combine the simple FOR with FOR /F. But of course this only works if none of the strings contain * or ?
Code: Select all
@echo off
for %%S in (
"1,Martini Shaker"
"2,Wine Bottle"
"3,Beer Glass"
) do for /f "tokens=1,2 delims=," %%A in ("%%~S") do echo T1=%%A T2=%%B
Dave Benham