You can use the double quotation mark as a delimiter with syntax like:
FOR /F delims^=^"^ tokens^=2 %G IN ('echo I "want" a "pony"') DO @ECHO %G
When run on the command line, using tokens^=2
should give you want
, and 4 tokens gets you a pony.
Applying the technique to your original question, this should work in your batch file:
FOR /F delims^=^"^ tokens^=2 %%G IN ('FINDSTR /L "ProductShortName" "data.txt"')
Details
I'm no expert on quirks of the command line parser, but it may help to think of the usual "delims=blah tokens=blah"
as a single, combined argument passed to FOR. The caret escaping trick in delims^=blah^ tokens^=blah
bypasses the need for enclosing quotes while still treating the sequence as a single argument. I've used a bit of creative analogy here, and the effect isn't universal across the shell. E.g. you can't do dir C:^Program^ Files
(which makes sense since ^
is a valid filename character).
Test Cases
With sufficient escaping, you can quickly check your original sample on the command line:
FOR /F delims^=^"^ tokens^=2 %G IN ('echo ^^^<?define ProductShortName="Foo" ?^^^>') DO @ECHO %G
Others playing with this may want to create a file testcases.txt:
blah blah "red"
blah "green" blah
How about a "white" "unicorn"?
and run something like:
FOR /F delims^=^"^ tokens^=2 %G IN (testcases.txt) DO @ECHO %G
to check results for a variety of inputs. In this case it should yield:
red
green
white
One last example:
FOR /F delims^=^"^ tokens^=2 %G IN ('FINDSTR /L "unicorn" "testcases.txt"') ^
DO @ECHO The unicorn is %G.
Finally, note my testing for this was done on Windows Server 2003.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…