Tuesday, March 13, 2007

How to use the FOR command in DOS?

Oftentimes you may want to perform a repetitive operation to a list of items in the command prompt, the list could be a list of files, folders, or just any random list from a file.  This FOR command in DOS is all up for the task.

First, here is the general format of the command: FOR ... IN ... DO ....

FOR %variable IN (set) DO command [command-parameters]


%variable
a single letter replaceable parameter.
(set)
a set/list of one or more files.
command
the command to carry out for each file.
[command-parameters]
parameters or switches for the specified command.

To Iterate Local Folders Only

Use the /D option. e.g.
FOR /D %variable IN (set) DO command [command-parameters]
Example: To rename all the folders to "folder name".bak. FOR /D %i IN (*) DO ren "%i" "%i.bak"

To Iterate All Folders Recursively

Use the /R [[drive:]path] option.

Other Options

To see more options on the FOR command, type FOR /h in the command prompt, or see the Microsoft's page.