Page 1 of 1

for /f command?

Posted: 27 Aug 2009 21:50
by Billy885
This works fine and displays what I want it to:

Code: Select all

FOR /F "tokens=1,2,* delims= " %%i in (%path_filename%) do (
   if %%i == TIME echo.&echo    Time of day is: %%j

And here comes the but. When it finds a path or filename with spaces, it can not find the file. If I put " (quotes) around the variable it then will breaks the variable down and does not find "TIME" unless it is in the file name before the first space.

Any help will be appreciated! Thanks in advance.

Posted: 28 Aug 2009 09:34
by avery_larry
Hard to help you since we don't know what %path_filename% looks like.

But if you're using a space as the delimiter, and you don't have a controlled, constant number of spaces, then you really can't expect a for loop to work well.

If you show us some more of your code and/or tell us what you're trying to accomplish, we might be able to help with a "better" solution. For now, you'll probably have to do something like this:

Code: Select all

FOR /F "tokens=1-8 delims= " %%i in (%path_filename%) do ( 
   if "%%i" == "TIME" echo.&echo    Time of day is: %%j
   if "%%j" == "TIME" echo.&echo    Time of day is: %%k
   if "%%k" == "TIME" echo.&echo    Time of day is: %%l
   if "%%l" == "TIME" echo.&echo    Time of day is: %%m
   if "%%m" == "TIME" echo.&echo    Time of day is: %%n
   if "%%n" == "TIME" echo.&echo    Time of day is: %%o
   if "%%o" == "TIME" echo.&echo    Time of day is: %%p
)


Or perhaps this:

Code: Select all

FOR /F "tokens=1,2,* delims= " %%i in (%path_filename%) do ( 
   if "%%i"=="TIME" (
      echo.&echo    Time of day is: %%j
      ) else (
         FOR /F "tokens=2,3,* delims= " %%l in (%path_filename%) do (
            if "%%l"=="TIME" (
               echo.&echo    Time of day is: %%m
               ) else (
                  FOR /F "tokens=3,4,* delims= " %%o in (%path_filename%) do (
                     if "%%o"=="TIME" echo.&echo    Time of day is: %%p
                  )
            )
         )
   )
)

Posted: 29 Aug 2009 16:46
by Billy885
Sorry about that Avery.

The line in the file that I am trying to read is fixed on number of spaces.

The problem came up when the file name had spaces:

"Main Training Base Day.mis"

Then the above (%path_filename%) would only look for file "Main" and not find it because of the dos use of spaces as limiters.

To fix that I put quotes around ("%path_filename%"). Now it can find the file but then the for statement thinks that is the string I want to find "TIME" in and it is not.

I hope this helps. I dont think seeing more of the code will help as this is just a small part of a menu system and startup.

Posted: 30 Aug 2009 20:00
by DccD
You need to use the usebackq option in the FOR loop.

Code: Select all

FOR /F "usebackq tokens=1,2,* delims= " %%i in ("%path_filename%") do ...

Posted: 30 Aug 2009 21:12
by Billy885
Perfect! DccD and much appreciated! I knew I was missing something.