Iterate Over Files

Introduction

The following examples will demonstrate the use of "for" looping construction to iterate over files with a particular pattern.

Syntax :

for %%variablename in (pattern1 pattern2 .. ) do command

or

for %%variablename in (pattern1 pattern2 .. ) do
(
    command1
    command2
)

Let's prepare a folder containing 5 files with names listed below :
  • test1.html
  • test1.txt
  • test2.html
  • test2.txt
  • test3.html

Example 1

Problem : We want to create a batch file to echo each .html files only.  

Solution

Create a batch script named "process_files_1.bat". The script will iterate over a pattern with "*.html" as part of the nameset in our batch script. The complete batch script code shown below.

for %%in (*.html) do echo %%v

The result shown in the screenshot below.



Example 2

Problem : We want to create a batch file to echo each .html and .txt files.  

Solution : 

Create a batch script named "process_files_2.bat". The script will iterate over a pattern with "*.html *.txt" as part of the nameset in our batch script. The complete batch script code shown below.

for %%in (*.html *.txt) do echo %%v

The result shown in the screenshot below.



Comments