Page 1 of 1

Use Variables in FOR Loop tokens?

Posted: 05 Apr 2012 23:53
by tinfanide

Code: Select all

setlocal enableextensions enabledelayedexpansion

FOR /L %%A IN (1,2,7) DO (
   SET "num=%%A"
   FOR /F "tokens=!num!" %%G IN ("Mon Tue Wed Thur Fri Sat Sun") DO ECHO %%G
)

endlocal

PAUSE


I want
Mon
Wed
Fri
Sun


!num!" was unexpected at this time.
!num!" was unexpected at this time.
!num!" was unexpected at this time.
!num!" was unexpected at this time.
Press any key to continue . . .

Re: Use Variables in FOR Loop tokens?

Posted: 06 Apr 2012 02:39
by foxidrive
Delayed expansion doesn't work but this is a workaround.

Code: Select all

@echo off

FOR /L %%A IN (1,2,7) DO set num=%%A&call :next
goto :skip

:next
   FOR /F "tokens=%num%" %%G IN ("Mon Tue Wed Thur Fri Sat Sun") DO ECHO %%G
goto :EOF

:skip
pause

Re: Use Variables in FOR Loop tokens?

Posted: 06 Apr 2012 02:42
by abc0502
when using this:

Code: Select all

@echo off
setlocal enableextensions enabledelayedexpansion

FOR /L %%A IN (1,2,7) DO (
FOR /F "tokens=1" %%G IN ("Mon Tue Wed Thur Fri Sat Sun") DO ECHO %%G
)

endlocal

PAUSE

just removed the set command

It give me:

Code: Select all

Mon
Mon
Mon
Mon

Re: Use Variables in FOR Loop tokens?

Posted: 06 Apr 2012 03:02
by foxidrive
You didn't use %%A in tokens. It didn't work here either.

Re: Use Variables in FOR Loop tokens?

Posted: 06 Apr 2012 03:27
by tinfanide
Yes, it works.
In this case, cannot use EnableDelayedExpansion.
The CALL command seems to get to the next label and call it back to the FOR loop instead of, like, using GOTO which will never bring it back to the FOR loop.

Re: Use Variables in FOR Loop tokens?

Posted: 06 Apr 2012 05:49
by dbenham
Regarding the foxidrive solution: It can be made more flexible by passing the value as a parameter instead of defining and using a fixed variable. I don't like to create unnecessary variables.

Code: Select all

@echo off
FOR /L %%A IN (1,2,7) DO call :showDay %%A
exit /b

:showDay  DayOfWeekNum
FOR /F "tokens=%1" %%G IN ("Mon Tue Wed Thur Fri Sat Sun") DO ECHO %%G
exit /b


Dave Benham