Getting first N values (About using FOR's token)

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Meerkat
Posts: 89
Joined: 19 Jul 2015 02:27
Location: Philippines

Getting first N values (About using FOR's token)

#1 Post by Meerkat » 14 Jan 2016 09:49

Hi again guys!

While I am making another simple Batch game, I got stuck with this (game is unimportant):

I want a code that gets first N values of a space delimited input and stores them in variables. From my intuition, this should work:

Code: Select all

@echo off
setlocal enabledelayedexpansion
set "Input=A B C D E F G"

for /l %%A in (1,1,4) do (
   set "G=%%A"
   for /f "tokens=!G! delims= " %%B in (%Input%) do (
      set "X_%%A=%%B"
   )
)
set X_
::I expect A, B, C, D will be "catched"
pause

But the output gives:
Sample.bat wrote:!G! delims= " was unexpected at this time.
!G! delims= " was unexpected at this time.
!G! delims= " was unexpected at this time.
!G! delims= " was unexpected at this time.
Environment variable X_ not defined
Press any key to continue . . .

Again, thanks for helping guys! :D

Meerkat

Aacini
Expert
Posts: 1914
Joined: 06 Dec 2011 22:15
Location: México City, México
Contact:

Re: Getting first N values (About using FOR's token)

#2 Post by Aacini » 14 Jan 2016 10:33

The "tokens=" option can not include a delayed expansion variable (nor a FOR parameter). Use this:

Code: Select all

echo off
setlocal enabledelayedexpansion
set "Input=A B C D E F G"

set "G=0"
for %%A in (%Input%) do if !G! lss 4 (
   set /A "G+=1"
   set "X_!G!=%%A"
)
set X_
pause

What is the problem if more than 4 elements are defined?

Antonio

Post Reply