Guides:Shells/COMMAND.COM-CMD.EXE/DOS Commands/FOR

From CoderGuide

Jump to: navigation, search

FOR

Format:

FOR %var IN (set) DO command
FOR %t IN (*.txt) DO copy %t e:\backup

The FOR statement is a very useful command for working with multiple files. It will repeat a command for each file found to match the set, and set a variable with the name of the file found in each successful match.

Lets assume you have the following files in a directory:

TEST.TXT
HELLO.COM
STONED.COM
CODERED.EXE
BUGS.COM
JRCOOKBK.TXT
WARGAMES.BAS

So lets try running the FOR command:

C>echo off
FOR %f IN (*.TXT) DO echo %f
TEST.TXT
JRCOOKBK.TXT
echo on
C>

Note, that if the command is a batch file you're running, you need to use the CALL statement before the batch file you want to run:

FOR %a IN (*.bas) DO call batch.bat
Personal tools