Using FOR loop in batch files


Conditionally perform a command on several files.
      FOR %%parameter IN (set) DO command

   set         : A set of files, separated by any standard delimiter.

   command     : The command to carry out, including any 
                 command-line parameters.

   %%parameter : A replaceable parameter:
                 e.g. in a batch file use %%G 
                      (on the command line %G)

Copy a single file
FOR %%G IN (MyFile.txt) DO copy %%G d:\backups\

Copy a list of several files
FOR %%G IN (Myfile.txt SecondFile.txt) DO copy %%G d:\backups\
FOR %%G IN ("C:\demo files\file1.txt" "C:\demo files\File2.txt") DO copy %%G d:\backups\

Copy a single file
FOR %%G IN (c:\program^ files\MyFile.txt) DO copy %%G d:\backups\

In the line above the source folder has spaces that need to be escaped with ^

Although wildcards can be used an alternative method of processing files is to process the output of the command 'DIR /b'

This can be useful when you want to use some of the other DIR options like sorting.
FOR is an internal command.
"Darkness reigns at the foot of the lighthouse" ~ Japanese Proverb


FOR - Loop commands
FOR /R - Loop through files (recurse subfolders)
- Loop through several folders
FOR /L - Loop through a range of numbers
FOR /F - Loop through items in a text file
FOR /F - Loop through the output of a command
FORFILES - Batch process multiple files
GOTO - Direct a batch program to jump to a labelled line
IF - Conditionally perform a command
Equivalent bash command (Linux): for - Expand words, and execute commands