by Barry Dysert
(last updated May 26, 2014)
As you get more comfortable typing at the command prompt, you may want to explore what the For loop can do for you. Fundamentally, the For loop lets you execute commands over a set of items like files or directories. So, for example, if you want to perform the same activity over a set of files, using a For loop can provide tremendous time savings.
The general form of a For loop is:
FOR %variable IN (set) DO command [command-parameters]
Where "%variable" can be anything from "%a" through "%z"; the "set" is the list of space-separated file names on which you want to perform the "command"; and the "command-parameters" are an optional list of parameters to accompany the "command".
As an example, if you wanted to display to the screen the contents of files a.txt, b.txt, and c.txt you could do so using the following For loop:
FOR %i IN (a.txt b.txt c.txt) DO TYPE %i
If you have command extensions enabled, there are some additional forms of the For loop:
FOR /D %variable IN (set) DO command [command-parameters]
In this form, if "set" contains a wildcard character then it represents directories instead of files.
FOR /R [[drive:]path] %variable IN (set) DO command [parameters]
In this form, the loop walks the directory tree specified by "[[drive:]path]", executing the FOR statement in each directory along the path.
FOR /L %variable IN (start,stop,end) DO command [parameters]
In this form, the set is a sequence of numbers from "start" to "end", by "step" amount.
FOR /F ["options"] %variable IN (set) DO command [parameters]
In this form, "set" is one or more file names. Each file is opened, read, and processed before going on to the next file in "set". This particular form is quite powerful when "options" are specified. Details and examples can be found by typing "FOR /?" at the command line.
This tip (13118) applies to Windows 7 and 8.
The rename command can really be a timesaver over trying to do the similar sort of thing with Windows Explorer. You can ...Discover More
Displaying all the files a folder contains is an easy task in Windows. One way you can display the files is using command ...Discover More
The copy command can be a timesaver over trying to do the similar sort of thing with Windows Explorer. You can copy hundreds ...Discover More
FREE SERVICE: Get tips like this every week in WindowsTips, a free productivity newsletter. Enter your address and click "Subscribe."