The FOR command is a command that runs in the command line or batch processing to sequentially loop through a series of objects and execute the same or multiple commands. When combined with some programs in Windows management, its processing function is powerful, and its flexible and convenient application is impressive. However, its help information is also complex, often intimidating beginners. Here, based on my learning and understanding, I decompose and simplify its usage. Omissions and errors may be inevitable.
Basic format
(What is written here is the format used in the command line. If it is in a batch processing, you need to add an additional % in front of % to form %%):
for /parameter %variable in (set) do command
(Note: Except for the Chinese parts above, the rest are written according to its format requirements, and case does not matter)
Parameters: FOR has four types of parameters D L R F, and some parameters can also be attached with additional options, which will be introduced separately below.
Variable: (Remember that when using the FOR command in batch processing, the % in front of the variable should be changed to %%). This variable name is composed of a single letter and is case-sensitive (the original help says so. In actual application, it has been proved that using a single number as the variable name is also feasible), such as %B and %b represent different variables. The FOR command will assign the value read from in (set) to this variable in each loop, so that it can be referenced in subsequent commands.
Set: A set formed by a series of files, strings, or content generated by commands (of course, wildcards *? can be used, and environment variables can also be referenced). The FOR command reads the content in the set in a certain order and rule, assigns it to the variable, and executes the command after do, and then loops to the next round until the content in the set is read. The parentheses are necessary for the format (there should be a space between in and the following parentheses).
Command: It can be any qualified DOS command or an external program that can be called by DOS, and multiple commands can be enclosed in parentheses to be executed in one loop.
Note: Since some directories or file names may have spaces, in many cases, English quotes are often needed to enclose the content in the set and the command to indicate that it is a whole (but sometimes the content in the quotes may be regarded as a string). For the sake of brevity, the situation where the file name or directory name has spaces is ignored in some examples below.
Now, examples are explained by classifying parameters:
1. Parameter /d
for /d %%variable in (set) do command
The /d parameter specifies a FOR command that only operates on directories, not files.
Example 1:
Enter in the command line (not in batch processing, no more explanation later)
for /d %a in (c:\*.*) do echo %a
Running this will display all directories under the root directory of drive C one by one, and not display file names.
It looks a bit messy. If the command prompt echo is turned off, it will be clear:
for /d %a in (c:\*.*) do @echo %a
2. Parameter /R
The /R parameter can also be followed by a drive letter and path
for /r %variable in (set) do command
The path after /r refers to the entire directory tree under it (equivalent to the range in the DOS command tree). If it is only a single English period ., it refers to the directory tree under the current path. If the path is omitted, it specifically refers to the current directory. The in (set) later is equivalent to the file set matching each previous directory.
Here, it is divided into two cases according to whether there are wildcards in in (set)
1) There are no wildcards in in (set)
Specifies a single file or listed specific files (multiple file names are separated by separators such as spaces, commas, etc.)
Example 2
@echo off
for /r . %i in (abc.txt) do echo. > %i
echo on
Note: The path after for /r here is only a ., and echo. > %i in each subsequent loop is equivalent to creating a text file with only an empty line. The overall effect is to create an abc.txt in each directory under the current directory including subdirectories.
Example 3 (put in batch processing)
@echo off
rem Display the list of files named file1 and file2 in drive d:
for /r d:\ %%h in (file1,file2) do if exist %%h echo %%h
pause
2) There are wildcards * or? in in (set)
The do command here will process each item in the directory series specified by /r that contains the file in the in (set), and ignore those directories that do not contain matching files.
Example 4:
@echo off
rem Delete all *.chk files in drive c:
for /r c:\ %%h in (*.chk) do del /q %%h
pause
Note: del /q means delete in quiet mode (no confirmation is required)
3. Parameter /L
for /L %%variable in (start value, increment each time, comparison value at the end) do command
(The above L can also be in lowercase, mainly to avoid confusion with the number 1 visually, so it is not in lowercase)
(start value, increment each time, comparison value at the end) is equivalent to an arithmetic sequence of numbers. It starts from the number of "start value", increases by how much each time (can also be set to a negative number), and compares with the "comparison value at the end". If it exceeds, the FOR loop exits (and the do command for this round is not executed).
For example, (1,1,3) will generate the sequence (1 2 3); (1,2,9) will generate the sequence (1 3 5 7 9); (5,-1,1) will generate the sequence (5 4 3 2 1); (1,3,18) will generate the sequence (1 7 10 13 16)
Example 5
@echo off
:: Create five folders aa1~aa5 on drive d:
for /L %%i in (1,1,5) do md d:\aa %%i
pause
Note: A single colon : followed by a name at the beginning of a line is a label line, corresponding to the position pointed to by go in batch processing. The double colon :: is generally used for comments. Comments in batch processing can be expressed by rem plus a space. There is a slight difference. The rem comment will be displayed on the screen when the command echo is not closed, while :: will not be displayed in any case.
4. Parameter /f
This parameter /f will open the file in (set) so that the FOR command can process the reading and editing operations such as adding, deleting, and replacing of text files, which is very powerful, so it is relatively complicated.
File name - set
for /f "options" %variable in ("string" - set) do command
'Command' - set
Several options can be carried after /f. It is a qualified format without options. If parameters are carried, they must be enclosed in quotes as a whole. The set later is mainly formed by three forms. Finally, in each round in the FOR loop, a line of string will be formed to assign values to the specified %variable and additional variables derived from the options, and then execute the command after do.
The following uses examples to specifically explain and gradually understand the usage of each sub-item.
Example 6
Assume that the content of d:\abc.txt is as follows:
Name Gender Age Grade
Zhang San Male 36 A-1
Li Si Male 29 B-2
Zhao Liu Female 31 A-2
Execute the following command:
for /f %c in (d:\abc.txt) do @echo %c
Then the screen will display:
Name
Zhang San
Li Si
Zhao Liu
Explanation: This is the situation when %variable in for /r has no default parameter options. In each round of the loop, it will default to using spaces as separators, segment the lines in the opened file one by one. And because no additional variables are added (that is, only one variable %c), only the characters of the first segment are assigned to %c, then the command after do is executed, and then the next round of the loop is carried out, and empty lines are ignored by default.
Change it:
for /f "skip=1 tokens=1,4 delims= " %c in (d:\abc.txt) do @echo %c %d
Display as:
Zhang San A-1
Li Si B-2
Zhao Liu A-2
Explanation:
skip=1 means ignoring 1 line at the beginning of the text - ignoring several lines
delims= In a line, use what single symbol (can be a combination of multiple characters, no spaces between them, which are understood as multiple single characters. If a space character is needed, it must be placed at the end) to separate the string as the unit for reading and assignment (forming a segment). In this example, the empty after the equal sign means using only spaces to separate. - What knife to use to cut
tokens=1,4 The number after this equal sign means taking the first and fourth separated string segments in turn to assign to the %variable and the subsequent additional variables respectively. In this example, the first segment is assigned to %c, and the fourth segment is assigned to a variable after c, that is, assigned to %d. Moreover, it can be written as tokens=1,2,5-7 or tokens=1,2,3* or tokens=1,2,5,7, which respectively mean taking the 1st, 2nd, 5th, 6th, 7th (assigned to %c, %d, %e, %,f, %g in turn for 5 variables), 1st, 2nd, 3rd and all segments after 3rd (to assign to 3 variables), 1st, 2nd, 5th, 7th (to assign to 4 variables). The numbers after tokens can be out of order, but the writing order corresponds to the order of assigning to variables. This is assignment. As for whether to use it in the do command later is another matter. In other words -- the maximum number of segments to take.
The variable in (variable) represents the starting variable name. According to the total number defined in tokens, additional variable names are expanded. For example, if the total number is 3, then %c is additionally %d and %e. If it is %C, then %D%E... is additionally. In this example, tokens=1,4 only needs two. The starting one is %c in the parentheses of in (), so the first segment in each line is assigned to %c, and the fourth segment is assigned to variable %d.
Take the second line (the first line is skipped by skip=1) as an example. In "Zhang San Male 36 A-1" (also separated by spaces), it is cut into five segments by the knife of spaces. Only the 1st and 4th are needed, that is, Zhang San is assigned to %c, and A-1 is assigned to %d. Then @echo %c %d is executed, and then the next round... and empty lines are still omitted.
Change it a little more:
for /f "skip=1 tokens=4,1 delims=- " %c in (d:\abc.txt) do @echo %c %d
Then it will display:
A Zhang San
B Li Si
A Zhao Liu
Example 7
Assume that the content of d:\aa.txt is as follows:
Volume in drive D is MYDA
Volume Serial Number is C35D-8998
Directory of D:tmp
09/25/2001 10:40 AM 11,235 yg0925.txt
11/12/2001 04:29 pM 795 buple.txt
04/11/2002 04:18 AM 2,043 vitn.txt
3File(s) 12,673 bytes
0 Dir(s) 5,020,200,655 bytes free
Enter in the command line:
for /f "skip=5 tokens=5" %a in (d:\aa.txt) do @echo %a
It will display:
yg0925.txt
buple.txt
vitn.txt
free
Originally, I wanted to display the files listed in the file (of course, other commands can also be used to operate on the files). By skipping the first 5 lines with skip=5, and taking the fifth segment of each line after defaulting to separating by spaces with tokens=5, the file name is smoothly assigned to variable %a. The only drawback is that the last line takes a non-file name (of course, other methods can be used to handle this redundant one, but the format to ignore the last few lines is not provided in for/f). And the second last line has no fifth segment.
Obviously, the content in example aa.txt is the content after executing the dir command at a certain time. It can be established by using a similar command:
dir > d:\aa.txt
By the way, if appropriate parameters are added in dir /b, the redundant part can be avoided, and /ad can be added to only display directories, and /a-d can be added to only display files, etc.
Then, we can directly write the command and put it in the ('command' - set) after in.
for /f "skip=5 tokens=5 " %a in ('dir') do @echo %a
The effect is the same.
Note: The command set needs to be enclosed in single quotes to indicate that it is not a file set. If it is enclosed in double quotes, it indicates that it is a string set. This example is to illustrate the usage of the FOR command. If there is really such a use, the method in the "By the way" is also willing to be used. If nothing is displayed after you execute this example, you need to execute the command in the set first to see the format it displays. Maybe tokens=5 needs to be changed to tokens=4, and maybe the dir needs to be added with parameter /a-d to avoid displaying directories.
If the set is composed of multiple files, then after processing one file, it will process another file, and the number of loops (the number of times the do command is executed) will also be different due to different number of lines in each file.
If the set is composed of the system generated by commands, then you must first be familiar with the character system produced by the execution of the command, so as to correctly arrange the do command later.
The finishing touch: No matter what form the set after in is, for/f finally decomposes it into strings. According to whether "ignore several lines" (skip=), "use what knife to cut" (delims=), "take up to which segments" (tokens=), the strings formed in the set are segmented line by line and assigned to the variables after % or %% and possibly extended variables, so as to execute the command after do. Each line is a round of loop. This does not fully explain all parameters. Please use for/? in the command line to view. (The italicized words below are copied from the help content)
For example:
For file names with spaces, you need to enclose the file name in double quotes. To use double quotes in this way, you also need to use the usebackq option. Otherwise, the double quotes will be understood as defining a string to be analyzed. - In other words, when the usebackq (placed in the quotes after for /f) parameter is carried, the double quotes in in () still represent the file name.
There is another option eol=: The skip= mentioned above means ignoring the first few lines. In fact, by default, all lines starting with the semicolon ";" are also ignored. If you don't want to ignore the lines starting with semicolons, or want to ignore the lines starting with your own specified character, you can use the eol= your own defined character in the quotes after for /f. But it is not like delims= that can define multiple, only one can be defined.
Another trick: You can use the %~ operator to separate the file name into independent parts such as file name, extension, drive letter, etc. Please see the explanation in for/? (where the example variable is %I):
In addition, the replacement of FOR variable references has been enhanced. You can now use the following option syntax:
~I - Remove any quotes ("), expand %I
%~fI - Expand %I to a fully qualified path name
%~dI - Only expand %I to a drive letter
%~pI - Only expand %I to a path
%~nI - Only expand %I to a file name
%~xI - Only expand %I to a file extension
%~sI - The expanded path only contains short names
%~aI - Expand %I to the file attributes of the file
%~tI - Expand %I to the date/time of the file
%~zI - Expand %I to the size of the file
%~$PATH:I - Find the directory listed in the path environment variable and expand %I to the first fully qualified name found. If the environment variable name is not defined or the file is not found, this combination key will expand to an empty string.
You can combine modifiers to get multiple results:
%~dpI - Only expand %I to a drive letter and path
%~nxI - Only expand %I to a file name and extension
%~fsI - Only expand %I to a full path name with a short name
%~dp$PATH:I - Find the directory listed in the path environment variable and expand %I to the first drive letter and path found.
%~ftzaI - Expand %I to a DIR-like output line
Brief summary:凡是 %~ 打头的操作符,都是文件名或环境变量的分离操作。而每项要想运用自如,则需要付出辛勤的练习。
Practice: (I'm lazy, I won't do it myself...)
Traverse drives C and D, find the known file name (receive keyboard input), record its storage location and time in D:\mynote.txt. The record format is as follows:
XX year XX month XX day. After searching, the situation of file XX on drives C and D is as follows:
Time Location
...... ......
...... ......
...... ......
.
.
.
Tip: The DOS commands, variables, and parameters that may be used: echo, set, set/p, %date%, %~ >, >>.
Summary and tips:
The actual usage of the FOR command has basically ended, but this alone cannot write a powerful batch processing. It is only a DOS command. You need to be proficient in some other DOS commands and commands provided by the Windows system, and combine them to give full play to its powerful and practical functions, so that some complex things can be handled unexpectedly simply and conveniently.
Attachment: A common command or environment setting needed in the batch processing FOR command:
The FOR command actually loops. If the value of an environment variable is changed in the command of each round, in the default state, a FOR command uses %environment variable% to get the value only once, then when it is used again in the next round of the loop, it is still the value before the change (including during the execution of multiple commands in parentheses after do), which does not achieve the expected purpose. Therefore, the following command is introduced:
setlocal enabledelayedexpansion
Start the localization operation of environment changes in the batch processing file and start delayed environment variable expansion. When the end of the batch processing file is reached for EXECUTING SETLOCAL, there will be an implicit endlocal for each setlocal command of the batch processing file that has not been executed yet.
When getting the variable value, using!variable name! can get the value dynamically. Delayed environment variable expansion allows you to use a different character (exclamation mark) to expand the environment variable at execution time. This usage actually belongs to what all compound commands in batch processing need to pay attention to. If you do not want to retain the changed environment after the batch processing ends, it is recommended to always add setlocal.
If combined with some other more complex commands related to the system and network (such as wmic, net), then it is the time to show the heroism of FOR. For example, traversing local disks can use the command: wmic logicaldisk where "drivetype=3" get name. Obviously, it is very easy to search for a certain file in all disks and perform corresponding operations. Using the FOR command well also requires cooperation with other commands and computer basics. Hehe, my level is limited, and what I write is only at a low level... I hope it can help those who are learning the FOR command of DOS.
Transferred from CSDN, original website:
https://blog.csdn.net/houkai6/article/details/8514336