Sunday, November 16, 2008

Quotes In For Loop Set

One thing that just bit me the other day is how for /F loop treats a set enclosed in quotes as a literal string rather than a file name.  This is actually mentioned in the help for page, but still, this is something I did not anticipate.

Consider this example:

set FILEPATH=”c:\some dir with space\somefile.txt”

Now I wanted to go through the lines in that file, so naturally I tried to do this:

for /F %i in (%FILEPATH%) do (echo %i)

What do I get?  I get:


Why?  Well, it turns out for /F treats anything in the set with quotes as a string instead of a filename.  OK, so let me try without the quotes then.

set FILEPATH=c:\some dir with space\somefile.txt

for /F %i in (%FILEPATH%) do (echo %i)

But now I get this error:

The system cannot find the file c:\some.

So it refuses to recognize the filename with spaces if I remove the quotes.  So what to do then?  The ugly way, unfortunately.

set FILEPATH=”c:\some dir with space\somefile.txt”

for /F “usebackq” %i in (`type %FILEPATH%`) do (echo %i)