Use Variables in FOR Loop tokens?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
tinfanide
Posts: 117
Joined: 05 Sep 2011 09:15

Use Variables in FOR Loop tokens?

#1 Post by tinfanide » 05 Apr 2012 23:53

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 . . .

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Use Variables in FOR Loop tokens?

#2 Post by foxidrive » 06 Apr 2012 02:39

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

abc0502
Posts: 1007
Joined: 26 Oct 2011 22:38
Location: Egypt

Re: Use Variables in FOR Loop tokens?

#3 Post by abc0502 » 06 Apr 2012 02:42

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

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Use Variables in FOR Loop tokens?

#4 Post by foxidrive » 06 Apr 2012 03:02

You didn't use %%A in tokens. It didn't work here either.

tinfanide
Posts: 117
Joined: 05 Sep 2011 09:15

Re: Use Variables in FOR Loop tokens?

#5 Post by tinfanide » 06 Apr 2012 03:27

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.

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: Use Variables in FOR Loop tokens?

#6 Post by dbenham » 06 Apr 2012 05:49

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

Post Reply