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)



Unknown said...

Yeah, I don't get this either, why require ( ) at all if they are not used as a container "scope"

Lazzaro said...

you could also set the delims specification to "no delimiters", like this:

for /F "delims=" %i in (%FILEPATH%) do (echo %i)

Arif Sukoco said...

Thanks Lazzaro, I didn't know about the "no delimiters" trick. However doing it with "no delimiters" will echo the file path instead of the content of the file, which is what I wanted to do.

Another way to achieve the same effect as the "no delimiters" method is to use tokens=*

for /F "tokens=*" %i in (%FILEPATH%) do (echo %i)