Featured image of post The For Command in Windows Batch Scripts

The For Command in Windows Batch Scripts

The For command is a powerful tool for boosting efficiency in batch scripts!

Introduction

In our daily work, if you use Windows, making good use of batch commands, especially for bulk file and text processing, can greatly boost productivity and get twice the result with half the effort!

However, many people’s use of batch scripts stops at combining several commands to run together, saving the time of repeatedly typing commands and waiting. This is actually just the most basic way to use batch scripts.

But to unlock the full power of batch scripts, the for command is truly the core. As a tool that handles both loop processing and text-column processing, nothing rivals it when it comes to improving batch script efficiency!

Yet the for command is relatively complex to use, and many people may not have mastered it well. So in this article, we bring you a systematic introduction to this core command in batch scripting.

There’s also an Easter egg that Qiucao discovered: Microsoft actually has an official, long-standing bug that has never been fixed 😂😂😂

Introduction to the For Command

Let’s now take a detailed look at this heavyweight command in Windows batch scripting.

Basic Syntax

1
FOR %variable IN (set) DO command [command-parameters]
  • %variable: the for-loop variable; use %% in batch scripts and % when running directly from the command line
  • (set): can be a file, a directory, a string, or command output..
  • command: the command to execute for each iteration.
  • command-parameters: control loop behavior (such as /R, /D, /L, /F, etc.)

For example, to iterate over a set:

1
2
@echo off
for %%a in (苹果 香蕉 "西瓜 芒果") do echo 水果:%%a

Output:

1
2
3
水果:苹果
水果:香蕉
水果:"西瓜 芒果"
  • Note: by default, elements are separated by spaces, and a quoted string is treated as a whole.

** The /R Option: Recursively Traverse Files**

This option is used to recursively traverse files in a directory and its subdirectories.

1
2
@echo off
for /R "C:\Chengxiaqiucao" %%a in (*.txt) do echo 找到文件:%%a

Features:

  • Traverse all .txt files under C:\Chengxiaqiucao and its subdirectories.
  • %%a will contain the full file path (e.g. C:\Chengxiaqiucao\test\file.txt).

/D: Process Directories

This option traverses directories only (not files).

1
2
@echo off
for /D %%a in ("C:\*") do echo 目录:%%a

Features:

  • List all first-level directories under C:\ (such as Program Files, Users, etc.).

4. /L: Generate a Number Sequence

This option is similar to controlling the number of loop iterations when programming.

Syntax: for /L %%a in (start, step, end)

The following example generates an arithmetic sequence:

1
2
@echo off
for /L %%a in (1, 2, 10) do echo 当前数字:%%a

Output:

1
2
3
4
5
当前数字:1
当前数字:3
当前数字:5
当前数字:7
当前数字:9

/F: Advanced Text Parsing (The Core Option)

This option can be considered the most core option of the For command; in most cases, it’s what lets the For command truly shine.

It is mainly used to parse text, strings, or command output line by line, and it supports complex rules.

Syntax:
1
for /F ["选项"] %%a in (数据源) do 命令
  • Data source: a file, a string, or command output (wrapped in backticks `).
  • Options: delims, tokens, skip, eol, usebackq, etc.

Common Options of /F

OptionPurposeExample
delims=xyzDefine delimiters (default space/tab)delims=, split by comma
tokens=nExtract the nth column (separate multiple columns with commas, e.g. 1,3)tokens=2 extract the second column
skip=nSkip the first n linesskip=2 skip the first two lines
eol=;Define the line comment character (default ;)eol=# ignore lines starting with #
usebackqChange how the data source is quoted (see below)Handle paths with spaces or command output

The Role of usebackq

Easter Egg Here: A Bug in the Official Documentation

In the Chinese official Windows help, the description of the -F option is actually wrong.

As you can see, the description here for using usebackq is exactly the same as for not using it, and the Chinese translation is very awkward and hard to understand.

However, by running the chcp 65001 command to switch the command-line code page to UTF-8, the help is then displayed in English.

As you can see, this is much clearer. usebackq solves the problems in the following scenarios:

  1. Handle file paths with spaces: quote the filename with double quotes.
  2. Execute a command and parse its output: quote the system command with backticks `.
  3. Parse a string directly: quote the string with single quotes '.
Case 1:
1
2
@echo off
for /F "usebackq delims=" %%a in ("C:\My Files\data.txt") do echo %%a
  • Without usebackq, the spaces in the path would cause a parsing error.

** Case 2**

Parse data.csv (format: name,age,city), skip the header line, and extract the name and city.

Input file data.csv:

1
2
3
姓名,年龄,城市
张三,25,北京
李四,30,上海

Batch script:

1
2
3
4
@echo off
for /F "usebackq skip=1 delims=, tokens=1,3" %%a in ("data.csv") do (
    echo 姓名:%%a,城市:%%b
)

Output:

1
2
姓名:张三,城市:北京
姓名:李四,城市:上海

Application Scenario Summary

OptionApplicable ScenarioTypical Command Example
NoneIterate over a simple list of files or stringsfor %%a in (*.txt) do echo %%a
/RRecursively process files under a directoryfor /R %%a in (*.log) do del %%a
/DProcess directories onlyfor /D %%a in (C:\*) do echo %%a
/LGenerate a number sequence (e.g. a fixed number of loops)for /L %%a in (1,1,5) do echo %%a
/FParse text files, command output, or complex stringsfor /F "tokens=2" %%a in (data.txt)

So by mastering these options and techniques of the For command, you can fully turn it into a “Swiss Army knife” for handling files, text, and system tasks in batch scripts.


Built with Hugo
Theme Stack designed by Jimmy