Using FOR in Windows batch files

Posted: (EET/GMT+2)

 

If you need to perform the same operation on several files, the FOR command can save a considerable amount of typing in a Windows batch file.

For example, the following command displays the name of every text file in the current directory:

FOR %%f IN (*.txt) DO ECHO %%f

The variable %%f is replaced with the name of each matching file in turn. You can use the variable with other commands. For example, the following batch file copies all log files to another directory:

FOR %%f IN (*.log) DO COPY %%f C:\Backup

One detail worth remembering is that batch files use two percent characters for the variable. If you enter the FOR command directly at the command prompt, use only one:

FOR %f IN (*.txt) DO ECHO %f

FOR can do considerably more than simply iterate through filenames, but even this basic form is useful when automating repetitive file operations.

Type FOR /? at the command prompt for the available options.

Hope this helps!