HomePage > Scripts > Iterate FOR tokens

Iterate FOR tokens

Tags:  

So I was asked (dunno why!) to create sample cmd script code that finds 'the second to last token in a string as parsed by the FOR command'.

And here it is:


@echo off
setlocal
set COUNTER=0
FOR /F "tokens=*" %%a in ("1 2 3 4 5 6") do call :ITERATETOKENS %%a
goto :eof
:ITERATETOKENS
if not {%1} == {} (echo token # %COUNTER% = %1) && (set /a COUNTER = %COUNTER% + 1) else goto :END
shift
goto :ITERATETOKENS
:END
set /a SECONDLAST = %COUNTER% - 1
echo second to last value was %SECONDLAST%
goto :eof
endlocal



This is what the output looks like:

C:\>iterate.cmd
token # 0 = 1
token # 1 = 2
token # 2 = 3
token # 3 = 4
token # 4 = 5
token # 5 = 6
second to last value was 5

C:\>


I can imagine that this might be useful. I can't for the life of me think of any specific example of usefulness, though. C'est la vie.
         

0 Comments  Show recent to old
Post a comment


 RSS of this page