China DOS Union

-- Unite DOS · Advance DOS · Grow DOS --

Union site: www.cn-dos.net Forum site: www.cn-dos.net/forum
DOS stands for freedom, openness and progress. Let us work hard, learn from the openness and GNU spirit of FreeDOS and Linux, and together build and grow a free GNU GPL world!

中国DOS联盟论坛
The time now is 2026-07-29 19:07
中国DOS联盟论坛 » DOS批处理 & 脚本技术(批处理室) » [Original]*****FOR Statement Learning Guide***** View 7,535 Replies 30
Original Poster Posted 2008-03-11 18:29 ·  中国 北京 联通
中级用户
★★
替身
Credits 269
Posts 130
Joined 2007-03-23 21:41
19-year member
UID 82683
Gender Female
Status Offline
Due to the recent tight schedule, this article was written by me in the past two days. I hope everyone will forgive any errors! I truly hope everyone can fully master the key points of using the FOR statement....

After seeing the replies in the DOS Union, some people are eager to learn the FOR statement, and some have certain doubts about my plan to write this article about the FOR statement, which is already widely available. It seems I should still write it. First, to let experts give some pointers, and second, to review what I've learned by the way! Let me clarify: The following statements, if using the %? form, all run in the CMD command prompt; if using the %%? form, they run in a batch processing context!

1. FOR Statement
The form of for %a in (****) do @echo %a is the simplest one, without parameters such as /D, /R, /F, etc., and the usage is also very ordinary. Let's briefly introduce it to everyone below.

C:\>for %a in (aa.txt bb.txt cc.txt) do @echo %a
The running result is as follows:
aa.txt
bb.txt
cc.txt

Of course, we can also use wildcards.
for %a in (*) do @echo %a
for %a in (a?*.txt) do @echo %a
And so on, which are similar.

The FOR statement can simplify the repetition of running commands, improve the running speed to a certain extent, and reduce the amount of code.

for %a in (*.cmd *.txt) do @echo %a

Displays all files with the suffixes.CMD and.TXT in the current directory, which is convenient for processing multiple files.

Of course, we can also use it like this. Taking the %PATH% environment variable as an example, as follows:

for %a in ("%path:;=" "%") do @echo %~a

The running result is as follows:

C:\WINDOWS\system32
C:\WINDOWS
C:\WINDOWS\System32\Wbem

The purpose is to separate each path of the PATH environment variable and display them line by line.

2. FOR /D Statement
Open the CMD command prompt and enter the following statement in the legendary black box:

C:\>for /d %a IN (*) do @echo %a

9527
ccp
Documents and Settings
ppw
Program Files
RavBin
WINDOWS
WINNT

The result is as above, showing the names of each directory in the current directory, excluding file names. For (*) - the content in the parentheses is called "set". In fact, we can also run in the form of (*.*), which means all content. In fact, it is the wildcard we are familiar with. And my understanding of the role of /D is similar to a filtering effect (/D is the abbreviation of DIRECTORY), that is, only displaying directory names!

Similarly, we run the following statement:

C:\>for /d %a in (w*) do @echo %a
The result is as follows:

WINDOWS
WINNT

This statement displays the directory names starting with W! (case-insensitive)

C:\>for /d %a in (w*s) do @echo %a
WINDOWS

Needless to say, this is related to the usage of wildcards.

Let's talk about using? as a wildcard in the /D parameter.

C:\>for /d %a in (w?nnt) do @echo %a---Successfully executed. There is no need to say that there is the WINNT directory. If it is not executed successfully, it means there is no such directory.
WINNT

C:\>for /d %a in (w??nnt) do @echo %a--Not successful. Due to the characteristics of wildcards, it can only match directories like WIINNT.

C:\>for /d %a in (w?nnt?) do @echo %a--Successful. Also, why is it successful with two?? Because the last ending is the? wildcard, which can match directories like winnt winntt.
WINNT

Okay, let's stop talking about wildcards and continue...

3. FOR /R Statement
I understand that R in /R is the abbreviation of recursive, that is, the meaning of recursion.

Recursion means operating on all files in its directory and subdirectories. This is all due to the /R parameter. Let's give an example to illustrate the usage:

for /r %a in (*) do @echo %a is the same as for /r. %a in (*) do @echo %a. It has the same effect. Not specifying or using. means the current directory.

The function of this sentence is to display all files in the current directory and its subdirectories. Of course, we can also specify the directory we want to operate.

for /r d:\ansi %a in (*.txt) do @echo %a

Displays the names of all.TXT files in the D:\ANSI directory and its subdirectories.

If the directory name we specify contains spaces, we can use double quotes to solve it.

for /r "c:\program files" %a in (ok.*) do @echo %a

In this way, we can display all files with the file name OK in the c:\program files directory and its subdirectories.

Although the official help of the FOR /R statement mentions that if the content of the set is a dot, it can list the directory tree, but I always feel uncomfortable. Sometimes there is no need to be lazy for the sake of beauty. In fact, we can use the combination of /D and /R parameters to list the directory tree, as follows:

for /d /r "c:\program files" %a in (*) do @echo %a---Beautiful

for /r "c:\program files" %a in (.) do @echo %a ----Feels uncomfortable

In this way, we can list all directories and their subdirectories (excluding files) under the c:\program files directory. It is also acceptable to set the set as a dot.

4. FOR /L Statement
FOR /L %%parameter IN (start,step,end) DO command We can view this statement like this, which is convenient for everyone to understand.

for /l %a in (1,1,10) do @echo %a ------Display in positive order

for /l %a in (10,-1,0) do @echo %a------Display in reverse order

Circularly display these 10 numbers from 1 to 10. We can modify these numbers at will, but we should pay attention to some problems, as follows:

(start,step,end)

When step is positive, end >= start

When step is negative, end <= start

When step is zero, the situation is as follows:

start>end  Invalid operation

start<=end Infinite loop

We also need to know that other delimiters can be used between these three numbers, for example:

for /l %a in (1,1,10) do @echo %a
for /l %a in (1 1 10) do @echo %a
for /l %a in (1=1=10) do @echo %a
for /l %a in (1,1,10) do @echo %a
for /l %a in (1<tab>1<tab>10) do @echo %a

The running effects of these five statements are the same, <tab>---TAB key.

5. FOR /F Statement

Finally, we come to the /F parameter. Many novices are not very good at mastering it. The key is to be flexible. After using it more, it will become habitual, and then it will be fine.....

First, we need to introduce the following options under the /F parameter:
   
   delims=xxx  Use xxx as the delimiter of the FOR statement, which can be multiple symbols or characters. The default value is a space.
   skip=n Skip the number of lines at the beginning of the file. The default value is zero. If SKIP=X (if X is 0 or negative, the statement execution will fail, because zero or negative is根本 meaningless).
   eol=; Refers to the end of a line comment character. The default refers to the semicolon (;).
tokens=n Refers to the token that the line is going to be replaced with that meets the conditions. The default value is 1.
   usebackq Use back quotes for the processing of the FOR statement. usebackq=use back quote (` `--belongs to back quotes).

  I know that for some descriptions of these options in the help of the FOR statement, many people are not very clear about the content. The above description is not so easy to understand either. I just give a rough introduction. To truly understand the use of these options, we need to experience them in practical applications, which will better understand the meaning of these options.

  I will list a large number of examples to illustrate the use of each option:
  
  First, let everyone be clear that there are three forms when /F is processing:

 FOR /F "options" %? IN (file name) DO command
 FOR /F "options" %? IN ("string") DO command
 FOR /F "options" %? IN ('command') DO command   

1. Let's first talk about some applications of the DELIMS option

① for /f "delims==" %? in ('set') do @echo %?
Use the equal sign as the delimiter to process the result of the SET command running, and display all variable names.

 ② For example, we have an ansi.txt file with the following content: 
  
  AAA BBB CCC
DDD EEE BBB
UUU LLL PPP
   
  for /f "delims=" %a in (ansi.txt) do @echo %a We did not assign a value to the delims option, so there is no delimiter at all, that is, the entire content of the file is displayed, including the situation where there are spaces at the beginning and end of the line.

2. Some applications of the TOKENS option
 
 ① Let's also use the ansi.txt file for testing
  
  for /f "tokens=2" %a in (ansi.txt) do @echo %a

| AAA | BBB | CCC |
tokens=1 tokens=2 tokens=3

The default is to use space as the delimiter. TOKENS=2 gets the second token, so the above statement gets 3 values: BBB EEE LLL.

 ②for /f "tokens=*" %a in (ansi.txt) do @echo %a

tokens=* gets all tokens. In this case, the displayed result will remove the spaces before the beginning of the line, but not the spaces at the end of the line.
 For example:
 



This is just to show the position of the space. The result of executing the above statement is as follows:
 
 



 ③for /f "tokens=1,3-5*" %a in ("A B C D E F G H") do @echo %a %b %c

A B C D E F G H
tokens 1 2 3 4 5 6 7 8
%a %b %c %d The last token is *, so all tokens from token 6 onwards are assigned to %e

 The final result is: A C D E F G H

3. EOL option
 
  Many people don't pay too much attention to this EOL option when using the FOR statement. In fact, it is quite annoying.

  We all know that the eol option in the FOR statement defaults to ignoring lines starting with semicolon (;)

  for /f "eol= delims=" %a in (" Hello World!") do @echo %a-----No display, ignoring the line starting with space.

  for /f "delims= eol=" %a in (""Hello World!^") do @echo %a----No display, ignoring the line starting with double quotes.


  The two statements are different in meaning even though the eol and delims options are swapped.

  The first eol is in front, eol= means ignoring the line starting with space!!!

  The second eol is at the end of the options. In fact, it will ignore the line starting with double quotes. Isn't it annoying!
  
  From this, it can be seen that no matter where the EOL option is, it is based on the character after the equal sign as the judgment standard.

  So how do we solve this tricky problem?

  We can use some rarely used special characters or symbols as the value of EOL. Although it is not perfect, it should be able to cope with general situations!

For example: for /f "eol=backspace delims=" %%a in ("xxxxxxxxxxxx") do @echo.%%a

In fact, the most crucial thing to solve a problem is how we look at this problem!

4. SKIP=n option
  
  This option is actually nothing to say. Everyone also knows it, and there is no special usage. Just pay attention to a few problems.

  First, the value of n cannot be 0 or negative, otherwise an error will be reported! This is also reasonable.

  for /f "skip=5" %a in (xxx.txt) @echo.%a

Skip the first 5 lines of the xxx.txt file, and then operate. Of course, we can also use the following statement to achieve:

for /f "skip=00000000005" %a in (xxx.txt) @echo.%a Hehe, as long as there are numbers after 0, the effect is the same. Of course, if you specify a SKIP value greater than the number of lines in the file itself, there will be no display!!!



5. USEBACKQ option using back quotes

  Actually, when I first learned the FOR statement, I really didn't understand what was good about the back quotes mentioned in its help? I also didn't understand the meaning it mentioned. I have poor comprehension ability.

  ① When the set is executed in the back quote form, this option must be used.
   
  for /f "usebackq delims==" %a in (`set`) do @echo %a
  
② When the file name contains spaces, the USEBACKQ option can be used to handle it, which is very convenient.

  for /f "usebackq tokens=*" %a in ("c:\hello world.txt") do @echo.%a

By default, the FOR statement cannot add double quotes when processing files. Double quotes are used when processing in the form of a string!
  
  If we use the following statement, it will go wrong: 
 
  for /f "tokens=*" %a in (c:\hello world.txt) do @echo.%a 

  Because the object it processes is the hello file, not the hello world.txt file. I hope everyone can distinguish this clearly.

③ Then, if we want to use the usebackq option and also process the string, what should we do? Do we also use double quotes? No, we use single quotes.

for /f "usebackq delims=" %a in ('Hello Word!') do @echo.%a

I saw on some foreign websites that if the string contains double quotes, we can use usebackq to process it, that is, the following example:

  for /f "usebackq delims=" %a in ('Hello "AnsiPeter" Word!') do @echo.%a

In fact, the normal statement can also be displayed normally. Using the USEBACKQ option may be convenient for distinction. I think so, as follows:

  for /f "delims=" %a in ("Hello "AnsiPeter" Word!") do @echo.%a


Okay, basically these options are finished. Now let's talk about some problems that need attention:

 
  for /f "tokens=1,2,3 delims=. " %a in ("a.b.c d.e f") do @echo %a %b %c

  This is a very ordinary FOR statement

  The execution result is: a b c   The delims option uses space and. as delimiters. What will happen if it is changed to the following?

  for /f "tokens=1,2,3 delims= ." %a in ("a.b.c d.e f") do @echo %a %b %c

  Error, there should not be." here. Why is this?

  I understand it like this. Each option in the FOR/F statement is separated by space, but except for the eol option, because the eol option is based on the character after the equal sign as the judgment standard, no matter where EOL is in the option, it is the same. We have introduced it above.

  In the following:

  for /f "delims= . tokens=1,2,3" %a in ("a.b.c d.e f") do @echo %a %b %c

  Error, needless to say, it defaults to taking. as one of the options of the FOR statement /F, but it doesn't include this option, so it will definitely report an error. In the following:


  for /f "delims=. tokens=1,2,3" %%a in ("a.b.c d.e f") do @echo %a %b %c

  There are two spaces after. in this sentence. What is the execution result? As follows:

  Result: a b c d

  This shows that the space is not regarded as a delimiter at all. If it is regarded as a delimiter, the result should be: a b c.

  Also as follows:

  for /f "delims= tokens=1,2,3" %%a in (" hello world ansi") do @echo %%a
  Display result: hello world ansi

  for /f "tokens=1,2,3 delims= " %%a in (" hello world ansi") do @echo %%a
  Display result: hello

  The delims is also a space behind, why is there a difference?

  The first statement has not assigned any value to delims, no matter how many spaces are behind it, it is the same, that is, there is no delimiter at all, so it is displayed in full.

  The second statement is because the delims option is the last one, they are ended with double quotes, so it is a space as the delimiter. So we still can't use double quotes as the value of the delims option.

   

[ Last edited by ansipeter on 2008-3-12 at 12:23 PM ]
Recent Ratings for This Post ( 3 in total) Click for details
RaterScoreTime
lxmxn +20 2008-03-11 22:02
clonecd +2 2008-03-13 15:43
batch +1 2008-07-29 18:40
Floor 2 Posted 2008-03-11 20:42 ·  中国 福建 泉州 电信
银牌会员
★★★
Credits 1,276
Posts 469
Joined 2002-12-23 13:00
23-year member
UID 586
Gender Male
From 福建泉州
Status Offline
Well written in detail, good, support the original poster.
QQ:366840202
http://chenall.net
Floor 3 Posted 2008-03-11 22:02 ·  中国 湖北 武汉 电信
版主
★★★★★
Credits 11,386
Posts 4,938
Joined 2006-07-23 17:10
20-year member
UID 59080
Status Offline
for %a in ("%path:;=" "%") do @echo %~a

This is the most classic!

I used to use sed to separate paths (echo %path% | sed "s/;/\n/"), but today I saw this and learned it.
Floor 4 Posted 2008-03-11 23:01 ·  中国 广东 深圳 龙岗区 电信
初级用户
Credits 89
Posts 36
Joined 2007-12-20 15:37
18-year member
UID 106247
Gender Male
Status Offline
Got it, thanks for sharing. You've worked hard.
Floor 5 Posted 2008-03-11 23:38 ·  中国 北京 电信
新手上路
Credits 10
Posts 5
Joined 2008-03-11 22:46
18-year member
UID 112681
Gender Male
Status Offline
Okay, I've been looking for this for a long time. Thanks a lot
Floor 6 Posted 2008-03-23 20:44 ·  中国 江苏 徐州 电信
新手上路
Credits 8
Posts 4
Joined 2008-03-23 20:08
18-year member
UID 113801
Gender Male
Status Offline
Floor 7 Posted 2008-03-24 12:18 ·  中国 安徽 合肥 电信
初级用户
Credits 27
Posts 25
Joined 2008-03-17 14:52
18-year member
UID 113207
Gender Male
Status Offline
Floor 8 Posted 2008-03-24 12:56 ·  中国 广东 深圳 鹏博士宽带
新手上路
Credits 8
Posts 5
Joined 2008-01-30 17:07
18-year member
UID 109848
Gender Male
Status Offline
First, I'll top it, then study it slowly. Thanks to the LZ.
Floor 9 Posted 2008-04-09 19:35 ·  中国 浙江 温州 平阳县 电信
新手上路
Credits 16
Posts 8
Joined 2007-03-29 23:19
19-year member
UID 83322
Gender Male
Status Offline
It's really classic,, at least, I can still understand it, feeling, um, very good,, bookmarked.
Floor 10 Posted 2008-04-10 12:40 ·  中国 安徽 安庆 桐城市 电信
新手上路
Credits 4
Posts 2
Joined 2008-04-10 11:42
18-year member
UID 115456
Gender Male
Status Offline
Floor 11 Posted 2008-04-10 17:06 ·  中国 江苏 苏州 电信
新手上路
Credits 14
Posts 6
Joined 2008-04-10 14:37
18-year member
UID 115476
Gender Male
Status Offline
Originally posted by lxmxn at 2008-3-11 10:02 PM:
for %a in ("%path:;=" "%") do @echo %~a

This is the most classic!

I used to use sed to separate paths (echo %path% | sed "s/;/\n/"), but today I learned about this. Study it.


I don't understand the bold part. Can the moderator explain it? Okay?

[ Last edited by wqh on 2008-4-10 at 05:14 PM ]
Floor 12 Posted 2008-04-11 08:52 ·  中国 广东 广州 白云区 电信
初级用户
Credits 25
Posts 11
Joined 2007-05-18 00:40
19-year member
UID 88882
Gender Male
Status Offline
Nice
Floor 13 Posted 2008-04-11 10:34 ·  中国 四川 眉山 电信
新手上路
Credits 16
Posts 8
Joined 2008-04-11 09:57
18-year member
UID 115567
Gender Male
Status Offline
Learning, DOS is really a long time no see
Floor 14 Posted 2008-04-13 17:39 ·  中国 湖北 武汉 电信
中级用户
★★
Credits 471
Posts 207
Joined 2007-05-03 14:53
19-year member
UID 87369
Gender Male
Status Offline
Originally posted by wqh at 2008-4-10 05:06 PM:

I can't understand the bold part. Can the moderator explain it? Is that okay

[ Last edited by wqh on 2008-4-10 at 05:14 PM ]

Try the following command in the command line to know the reason:
echo ("%path:;=" "%")
Floor 15 Posted 2008-04-13 19:30 ·  中国 广东 广州 白云区 电信
初级用户
Credits 25
Posts 11
Joined 2007-05-18 00:40
19-year member
UID 88882
Gender Male
Status Offline
Bump up..Looking back later
Recent Ratings for This Post ( 1 in total) Click for details
RaterScoreTime
xyzzhu +1 2008-07-26 07:46
Forum Jump: