A batch file is a simple text file that contains a series of commands to be executed sequentially by the Command Prompt in Windows. Batch files can be used to automate repetitive tasks, run programs, or perform file and folder operations.
One important feature of batch files is the ability to create loops, which is repeating certain commands for each element in a data set. By using loops, you can save time and effort in writing and running batch files.
In this article, we will explain how to use batch for loop files in Windows, including syntax, examples, and useful tips. We will also cover some variations of the for loop, such as for /f, for /r, and for /d, which can be used to process text files, subfolders, or directories. After reading this article, you will be able to create more efficient and flexible batch files by using for loops.
What is Batch File For Loop?
A batch for loop file is a control structure that allows you to execute a specific command for each element in a data set. The data set can be a list of values, a range of numbers, or the result of another command.
The commands executed by the for loop are referred to as command blocks, and can consist of one or more lines. For each iteration of the loop, the current value of the element will be stored in a variable, which can be used in the command block.
The basic syntax of a for loop batch file is as follows:
FOR %%parameter IN (set) DO command
Where:
- The %%parameter is a variable that stores the current value of the element. This variable must be prefixed with two percent signs (%%) if used in a batch file, or one percent sign (%) if used directly at the Command Prompt.
- (A set is a collection of data to be processed by a loop. This set can be a list of values separated by spaces, commas, or semicolons, or a range of numbers specified with the format  (start,step,end). This set can also be the result of another command enclosed in single quotes (‘), such as  ‘dir /b’ or  ‘type file.txt’.
- command is the command to be executed for each element in the set. This command can be an internal or external command, batch file, or command list. The variable %%parameter% can be used in this command to refer to the current value of the element. If the command consists of more than one line, it must be surrounded by parentheses (( and )).
Example:
FOR %%A IN (1 2 3) DO ECHO %%A
The above command will display the numbers 1, 2, and 3 sequentially on the screen.
FOR %%B IN (1,2,10) DO ECHO %%B
The above command will display the numbers 1, 3, 5, 7, and 9 sequentially on the screen. This is because the number range  (1,2,10) means starting at 1, increasing by 2 each step, to a maximum of 10.
FOR %%C IN ('dir /b *.txt') DO TYPE %%C
The above command will display the contents of all text files present in the current directory.
How to Use Batch File For Loop to Process Files and Folders?
One of the common uses of batch file for loops is to process files and folders in bulk. For example, you may want to rename, delete, or move a number of files or folders in a specific pattern. To do this, you can use some of the additional options available for for loops, such as:
- /FÂ to process text files or results from other commands.
- /RÂ to process subfolders recursively.
- /DÂ to process directories only.
Here is the syntax of the for loop batch file with these additional options:
FOR /F ["options"] %%parameter IN (set) DO command
Where:
- [“options”]Â are additional options that can be used to control how the for loop processes text files or command results. Some commonly used options are:
FOR /R [[drive:]path] %%parameter IN (set) DO command
Where:
- [[drive:]path]Â is the starting directory to be processed by the loop. If not specified, the current directory will be used.
- (set) is the set of files to be processed by the loop. This set must be a file matching pattern (file globbing), such as  *.txt  or  ?.bat. If this set is empty, then all files will be processed.
FOR /D %%parameter IN (set) DO command
Where:
- (set) is the set of directories to be processed by the loop. This set must be a file matching pattern (file globbing), such as  * or ?. If this set is empty, then all directories will be processed.
Example:
FOR /F "skip=1 delims=," %%A IN (data.csv) DO ECHO %%A
The above command will skip the first line of the data.csv file, which usually contains the column headings, and display the first column value of each subsequent line, separated by commas.
FOR /F "tokens=1,2* usebackq" %%A IN ("file name.txt") DO ECHO %%A %%B %%C
The above command will process a text file whose name contains spaces, and display the first, second, and remaining column values of each line, separated by spaces or tabs.
FOR /R C:\Users\ %%D IN (*.jpg) DO COPY %%D D:\Backup\
The above command will search for all files with the .jpg extension in the C:\Users\ directory and its subdirectories, and copy them to the D:\Backup directory.
FOR /D %%E IN (*) DO RMDIR /S /Q %%E
The above command will delete all directories and their contents in the current directory.
Other Interesting Articles
How to Use Batch File For Loop to Access File and Folder Information?
In addition to processing files and folders with the batch file for loop, you can also access information about them, such as name, extension, size, modification date, attributes, and path.
To do this, you can use path modifiers on loop variables. A path modifier is a special character that can be added after the percent sign (%) in a loop variable to change the value of that variable.
Here are some commonly used path modifications:
- %~fparameter to display the full path of a file or folder.
- %~nparameter` to display file or folder names without extensions.
- %~xparameter to display file or folder extensions.
- %~sparameter to display the short path of a file or folder, which is useful if the path contains spaces.
- %~zparameter to display the file or folder size in bytes.
- %~tparameter to display the date and time of file or folder modification.
- %~aparameter to display file or folder attributes, such as R (read-only), H (hidden), S (system), etc.
Example:
FOR %%F IN (*.txt) DO ECHO %%F %%~nF %%~xF %%~sF %%~zF %%~tF %%~aF
The above command will display information about all text files in the current directory, such as name, extension, short path, size, modification date, and attributes.
How to Use Batch File For Loop to Create Relative Paths?
One of the challenges you may face when using a batch file for loop is how to create a relative path of the file or folder processed by the loop. A relative path is a path that does not contain the initial drive or directory name, but only a part of a different path from the current directory.
For example, if the current directory is C:\Users\Alice\Documents, then the relative path of the file C:\Users\Alice\Pictures\image.jpg is …\Pictures\image.jpg.For example, if the current directory is C:\Users\Alice\Documents, then the relative path of the file C:\Users\Alice\Pictures\image.jpg is …\Pictures\image.jpg.
Creating relative paths can be useful if you want to move, copy or rename files or folders to a different location, but keep the original directory structure. For example, you might want to move all text files from the C:\Users\Alice\Documents directory and its subdirectories to the D:\Backup directory, but keep the subdirectories.
To create relative paths with batch for loop files, you can use some of the following techniques:
- Uses the environment variable “CD” to obtain the current directory, and removes it from the full path of the file or folder by using the “SET” command.
- Use the /V:ONÂ option to enable delayed variable expansion, and use an exclamation mark (!) as a variable delimiter instead of a percent sign (%). This is useful if you want to change the value of a variable in a loop.
- Uses the commands “PUSHD” and “POPD” to change the current directory while in the loop, and uses a period (.) to refer to the current directory.
Example:
@ECHO OFF SETLOCAL ENABLEDELAYEDEXPANSION FOR /R C:\Users\Alice\Documents %%G IN (*.txt) DO ( SET "source=%%G" SET "destination=!source:%CD%=!" ECHO !destination! ) ENDLOCAL
The above command will search for all text files in the C:\Users\Alice\Documents directory and its subdirectories, and display their relative paths from the current directory. For example, if the current directory is C:\Users\Alice\Documents, then the relative path of the file C:\Users\Alice\Documents\Folder1\File1.txt is Folder1\File1.txt.
@ECHO OFF FOR /R C:\Users\Alice\Documents %%H IN (*.txt) DO ( PUSHD "%%~dpH" SET "source=%%H" SET "destination=%CD%\%%~nxH" ECHO %destination% POPD )
The above command will search for all text files in the C:\Users\Alice\Documents directory and its subdirectories, and display their full path using the current directory as a prefix. For example, if the current directory is D:\Backup, then the full path of the file C:\Users\Alice\Documents\Folder1\File1.txt is D:\Backup\Folder1\File1.txt.
Conclusion
Batch file for loop is a very useful feature for creating more efficient and flexible batch files. By using a for loop, you can repeat a specific command for each element in a data set, such as a list of values, a range of numbers, or the result of another command.
You can also use some of the additional options available for for loops, such as /F, /R, and /D, to process text files, subfolders, or directories. In addition, you can also access information about the files and folders processed by the loop, such as name, extension, size, modification date, attributes, and path, by using path modification on loop variables.
Finally, you can also create a relative path of the files and folders processed by the loop, by using several techniques such as removing the current directory from the complete path, enabling delayed variable expansion, or changing the current directory while in the loop.
Hopefully, this article is helpful for those of you who want to learn more about batch files for loops in Windows. If you have any questions or suggestions, please leave a comment below. Thank you for reading.