Loading...
 

Looping

Table of contents:

FOR Loops

Windows does almost all looping through FOR Loops. They are extremely powerful and if you've not mastered them, you should. Even from the command-line they can save you hours of typing. For loops come in several sizes:

  • Loops through lists (A B C D E...)

  • Loops through boundaries (1, 1, 10) (start, increment, end)

  • Loops through lines of a file ("filename")

  • Loops through results of a command ('some command that returns a line of output')

  • Loops through a group of files (*.ext)

Loop Through a List

Perhaps the simplist loop is the loop through a list. The list is specified in parens and the For command substitutes each in turn.

REM TESTLOOP1.CMD
FOR %%a in (this that theother) do @echo %%a

C:\WABS>TESTLOOP1.CMD
this
this
theother

LOOP Through a Boundary

In this loop you specify the boundaries within the parens (start, step and stop). Steps may be negative and the stop can be less than the start.

REM TESTLOOP2.CMD
FOR /L %%a in (10,-2,0) do @echo %%a
C:\WABS>TESTLOOP2.CMD
10
8
6
2
0

Loop Through a File

One of the more useful uses of For loops is the ability to iterate through the lines of a file. For /F will accomplish this.

REM TESTLOOP4.CMD
FOR /F %%a in (testfile.txt) do @echo Line:%%a

{CODE()}
C:\WABS>type testfile.txt
this
that
theother
C:\WABS>TESTLOOP3
Line:this
Line:That
Line:theother



Created by system. Last Modification: Wednesday 14 of May, 2008 22:55:59 EDT by gmartin.