Doscommand for usage

Source: Internet
Author: User

For help documentation

Execute a specific command on each file in a group of files.

FOR % variable IN (set) DO command [command-parameters]

% Variable specifies a single letter replaceable parameter.
(Set) specifies one or more files. Wildcard characters can be used.
Command specifies the command executed on each file.
Command-parameters
Specify parameters or command line switches for specific commands.

When using the FOR command in the batch processing program, use % variable to specify the variable
Instead of % variable. Variable names are case sensitive, so % I is different from % I.

If the command extension is enabled, the following additional FOR command formats will be
Supported:

FOR/D % variable IN (set) DO command [command-parameters]

If the set contains wildcards, it is specified to match the directory name instead of the file name.
Name match.

FOR/R [[drive:] path] % variable IN (set) DO command [command-parameters]

Check the directory tree with [drive:] path as the root and point
FOR statement. If no directory is specified after/R, the current
Directory. If the set is only a single point (.) character, the directory tree is enumerated.

FOR/L % variable IN (start, step, end) DO command [command-parameters]

This set indicates a sequence of numbers from start to end in incremental form.
Therefore, (, 5) will generate the sequence 1 2 3 4 5, (5,-) will generate
Sequence (5 4 3 2 1 ).

FOR/F ["options"] % variable IN (file-set) DO command [command-parameters]
FOR/F ["options"] % variable IN ("string") DO command [command-parameters]
FOR/F ["options"] % variable IN ('command') DO command [command-parameters]

Or, if usebackq is available:

FOR/F ["options"] % variable IN (file-set) DO command [command-parameters]
FOR/F ["options"] % variable IN ("string") DO command [command-parameters]
FOR/F ["options"] % variable IN ('command') DO command [command-parameters]

Filenameset is one or more file names. Continue to filenameset
Before the next file, each file has been opened, read, and processed.
Processing includes reading files, dividing them into lines of text, and then dividing each line
It is parsed into zero or more symbols. Then use the variable value of the found symbol string
Call the For loop. By default,/F is separated by each row of each file.
. Skip blank lines. You can specify the Optional options"
The parameter replaces the default parsing operation. This quoted string contains one or more
Specify keywords for different resolution options. These keywords are:

Eol = c-refers to the end of a line comment character (just one)
Skip = n-indicates the number of rows ignored at the beginning of the file.
Delims = xxx-refers to the delimiter set. This replaces the space and the hop key.
Default delimiter set.
Tokens = x, y, m-n-indicates which symbol of each row is passed to each iteration.
For itself. This leads to the allocation of additional variable names. M-n
Format is a range. Use the nth symbol to specify mth. If
The asterisks of the last character in the symbol string,
Then the extra variable will be resolved after the last symbol
Distribute and accept reserved text of rows.
Usebackq-specify that the new syntax is used in the following situations:
A string enclosed in quotation marks when executed as a command and a single
The quotation mark character is a text string command and can be used in filenameset
Use double quotation marks to expand the file name.

Some examples may help:

FOR/F "eol =; tokens = 2, 3 * delims =," % I in (myfile.txt) do @ echo % I % j % k

Analyzes each row in myfile.txt, ignores the rows headers with semicolons
The second and third symbols in each line are passed to the for program body. Use commas and/or
Space separator. Please note that the for program body statement references % I
Get the second symbol, reference % j to get the third symbol, reference % k
To obtain all the remaining symbols after the third symbol. For files with spaces
Name, You need to enclose the file name in double quotes. To make
Use double quotation marks. You also need to use the usebackq option. Otherwise, the double quotation marks will
It is understood that it is used to define a string to be analyzed.

% I is specified in the for statement. % j and % k are
Tokens = the option is specifically described. You can use tokens = a line
A maximum of 26 characters can be specified. If you do not try to figure out a symbol higher than the letter 'Z' or
'Z' variable. Remember that the FOR variable is a single letter, case sensitive, and global,
At the same time, no more than 52 instances are in use.

You can also use FOR/F to analyze the logic on adjacent strings. The method is,
Enclose the filenameset between the brackets in single quotes. In this way, the character
Strings are treated as a single input line in a file.

Finally, you can use the FOR/F command to analyze the command output. The method is
The filenameset between the brackets is converted into an anti-string. This string will
It is passed as a command line to a sub-CMD. EXE, and its output will be captured
Memory, and is analyzed as a file. Therefore, the following example:

FOR/F "usebackq delims =" % I IN ('set') DO @ echo % I

The names of environment variables in the current environment are enumerated.

In addition, the replacement of the FOR variable reference has been enhanced. You can now use the following
Option Syntax:

~ I-delete any quotation marks (") and extend % I
% ~ FI-extend % I to a fully qualified path name
% ~ DI-extend % I to only one drive letter
% ~ PI-only extend % I to one path
% ~ NI-extends % I to only one file name
% ~ XI-only extend % I to one file extension
% ~ The sI-extended path contains only short names.
% ~ AI-extend % I to file attributes
% ~ TI-extend % I to the date/time of the file
% ~ ZI-extend % I to the file size
% ~ $ PATH: I-find the directory of the environment variable in the PATH and extend % I
The first fully qualified name found. If the environment variable name
This key combination is extended
Null String

You can combine modifiers to get multiple results:

% ~ DpI-extend % I to only one drive letter and Path
% ~ NxI-only extend % I to one file name and extension
% ~ FsI-only extend % I to a complete path name with a short name
% ~ Dp $ PATH: I-search the directory of the environment variable in the PATH and extend % I
To the first drive letter and path.
% ~ FtzaI-extend % I to DIR similar to the output line

In the preceding example, % I and PATH can be replaced by other valid values. % ~ Syntax
Terminate with a valid FOR variable name. Select an uppercase variable name similar to % I
Easy to read and avoid confusion with case-insensitive key combinations.

Usage of for in dos

For/parameter % variable in (SET) do command
FOR is divided into four parameters: D L R F

1. Parameter/d
For/d % variable in (SET) do command
The/d parameter specifies to only execute the for command for the directory rather than the file.

2. Parameter/R
/R parameters can be followed by drive letters and paths
For/r can contain the PATH % variable in (SET) do command
The path after/r refers to all directories in the entire directory tree under it (equivalent to the range in the doscommand tree). If it is only an English sentence ., it refers to the directory tree under the current path. If the path is omitted, it refers to the current directory, and the later in (SET) is equivalent to the file set that matches the previous directory.
Here, there are two conditions for wildcard characters in (SET ).
1) in (SET) does not contain wildcards
Specifies a single file or a list of specific files (multiple file names are separated by separators, such as spaces and commas)
Example 2
@ Echo
For/r. % I in (abc.txt) do echo.> % I
Echo on
Note: There is only one path after for/r, and echo.> signature in each loop.
Example 3 (put into batch processing)
@ Echo off
Rem display d: list of all files in the drive named file1 and file2
For/r d: \ % h in (file1, file2) do if exist % h echo % h
Pause
2) in (SET) contains wildcards * or?
In this case, the do command will process each object in the in (SET) Directory Series specified by/r, regardless of the directories without matching files.
Example 4:
@ Echo off
Rem deletes all *. chk files in drive C.
For/r c: \ % h in (*. chk) do del/q % h
Pause
Note: del/q indicates deletion in quiet mode (no confirmation required)
3. Parameter/L
For/L % variable in (start value, value added each time, comparison value at end) do command
(L can also be used in lower case, mainly for the purpose of visually not confusing with number 1, but not using lower case)
(Start value, value added each time, comparison value at the end) is equivalent to an equi-difference digital sequence, starting from the number of the "start value" and increasing each time (can also be set to a negative number) it is "added each time" and compared with "compare value at End". If it exceeds the value, it exits the for Loop (or the do command after this round is not executed)
For example, (, 3) will generate a sequence (1 2 3); (, 9) will generate a sequence (1 3 5 7 9); (5) will generate a sequence (5 4 3 2 1); (, 18) will generate a sequence (1 7 10 13 16)
Example 5
@ Echooff
: Create aa1 ~ in disk D ~ Five aa5 folders
For/L % I in (1, 1, 5) do md d: \ aa % I
Pause

Note: At the beginning of a row, a single colon (:) is followed by a name, which is a label line and corresponds to the position indicated after go in batch processing. The double colon (:) is generally used for comments, annotations can be expressed by rem and space in batch processing. The two are slightly different. rem comments are displayed on the screen when the command is not turned off for display :: it is not displayed under any circumstances.

Iv. Parameter/f
This parameter/f will open the files in the (SET), so that the for command can handle the editing operations such as reading text files, adding, deleting, and replacing text files, which is powerful, therefore, it is relatively complicated.
File Name-Set
For/f "option" % variable in ("string"-set) do command
'COMMAND '-Set
/F can be followed by several options, without options, of course, it is also a qualified format, and parameters must be enclosed in quotation marks as a whole. The following sets are mainly composed of three forms, finally, in each round of the for Loop, a row of strings will be read to assign values to the specified % variable and the additional variable assigned to the option. Then, run the command after do.
The following is an example to illustrate 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, etc.-level
Michael Zhang 36 A-1
Li Si Men 29 B-2

Zhao liunv31 A-2

Run the following command:
For/f % c in (d: \ abc.txt) do @ echo % c
The screen is displayed as follows:
Name
Zhang San
Li Si
Zhao Liu

Explanation: This is the default parameter option for/r before "% variable". In the loop, each wheel is separated by space by default and segmented to strings line by line in the open file, because no additional variable (that is, only one variable % c) is added, only the character in the first segment is assigned to % c, and then the do command is executed, and then the next round of the loop is carried out, empty rows are ignored by default.
Modify:
For/f "skip = 1 tokens = 1, 4, delims =" % c in (d: \ abc.txt) do @ echo % c % d
Shown:
Zhang San A-1
Li Si B-2
Zhao Liu A-2

Solution:
Skip = 1 indicates that the number of lines that the text begins to ignore is 1-ignore several lines
Delims = what single symbol can be used in a row (there can be a combination of multiple characters, and spaces cannot be added between them. It is understood as multiple single characters. If a space character is required, it must be placed at the end) to separate strings as the unit for reading values (forming a segment). In this example, after a medium number, it is null to separate strings with spaces. -- What knife is used for splitting
Tokens = the number after the equal sign indicates to take the nth separated string segment in order to assign the % variable and the variable appended with the sequence respectively, in this example, the first section is assigned to % c, and the second section is assigned to c. The variable is assigned to % d, and can be written as tokens = 1st, 5-7 or tokens =, 3 * or tokens =, 5, 7 respectively indicate to take 1, 2, 5, 6, 7 (in turn assigned to % c, % d, % e, %, f, % g contains 5 variables), 1, 2, 3, and 3 (three variables to be assigned), 1, 2, 5, 7 (four variables to be assigned ), the number after tokens = can not be in order, but the order of writing corresponds to the order allocated to the variable. This is a value assignment. It is not necessary to use the do command later. In other words, which segment can be used at most?
The variable in (variable) represents the name of the starting variable, which is expanded by the total number defined in tokens. For example, the total number is 3, % c attaches % d and % e, and % C attaches % D % E... In this example, tokens = 4th requires only two values. The starting value is % c in the in () Brackets. Then, the first section in each line is assigned to % c, and section is assigned to the variable % d.
Take the second line (the first line is skip = 1 skipped) as an example, in the "Zhang sanmale 36 A-1" (is also separated by spaces) a total of five segments by a space knife, as long as 1st, 4, namely three assigned to % c, A-1 assigned to % d, execute @ echo % c % d and then next round... Empty rows are also removed.

Make a few changes:

For/f "skip = 1 tokens = 4,1 delims =-" % c in (d: \ abc.txt) do @ echo % c % d

Displayed:
A zhangsan
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 AM 11,235 yg0925.txt
11/12/2001 pM 795 buple.txt
04/11/2002 AM 2,043 vitn.txt
3 File (s) 12,673 bytes
0 Dir (s) 5,020,200,655 bytes free

On the command line, enter:
For/f "skip = 5 tokens = 5" % a in (d: \ aa.txt) do @ echo %
Will display:
Yg0925.txt
Buple.txt
Vitn.txt
Free

The intention is to display the files listed in the file (of course, you can also use other commands to operate the file)
Ignore the first five lines through skip = 5. After tokens = 5 is separated by spaces by default, the file name is successfully assigned to the variable %, in the United States, the last row is not named by the file name (of course, other methods can be used to process this redundant, but the format of the last few rows is not provided in for/f ), the second to the last row has no fifth segment.
Obviously, the content in aa.txt is the content after the dir command is executed. It can use similar commands:
Dir> d: \ aa.txt to create
If you add a proper parameter/B to the dir, you can avoid unnecessary parts, add/ad to only display directories, and add/a-d to only display files.
Therefore, we can directly write commands into the ('COMMAND '-set) after in.
For/f "skip = 5 tokens = 5" % a in ('dir') do @ echo %

The effect is the same.
Note: The command set must be enclosed in single quotes to indicate that it is not a file set. If it is enclosed in double quotes, it indicates it is a string set. This example is used to describe the usage of the for command, if there is such a purpose, you are also willing to use the method described above. If nothing is displayed after you execute this example, You need to first execute the command in the set to view the display format, you may need to change tokens = 5 to tokens = 4. You may also need to add the/a-d parameter to the dir to avoid displaying the directory.
If the set is composed of multiple files, after processing one file, it processes another file. The number of lines of each file varies by the number of cycles (the number of do commands) it will also be different.
If the set is a command-generated system, you must first be familiar with the character system that will produce the effect after the command is executed, in order to correctly arrange the following do command

Eye-catching: No matter which form of the in set, for/f is finally decomposed into strings and whether to "ignore several lines" (skip =) as needed), "What knife is used to split" (delims =), "Which segments are the most required?" (tokens =, the variable assigned to % or % and the variable that may be extended out by line-by-line are executed to execute the do command. Each row is a round of loop. All parameters are not completely described here. Use for/? In the command line /? View. (The italics below are the content in the help of copying)
For example:
For file names with spaces, you must enclose them in double quotation marks. To use double quotation marks in this way, you also need to use the usebackq option. Otherwise, double quotation marks are interpreted as defining a string to be analyzed. -- In other words, when the parameter usebackq (placed in the quotation marks after for/f) is included, double quotation marks in () indicate that the file name is still.
Another option is eol =: skip = indicates to ignore the first few rows. In fact, by default, all rows starting with semicolons (;) are ignored, if you want to ignore the rows starting with a semicolon or ignore the rows starting with a specific character, you can use eol = your own character in the quotation mark parameter after for/f, but unlike delims =, it can define multiple, and only one can be defined.

Another example: % ~ The operator separates file names into separate parts, such as file names, extensions, and drive letters. for more information, see /? (The sample variable is % I ):
In addition, the replacement of the FOR variable reference has been enhanced. You can use the following syntax:

~ I-delete any quotation marks (") and expand % I
% ~ FI-extend % I to a fully qualified path name
% ~ DI-only expand % I to one drive letter
% ~ PI-only expand % I to one path
% ~ NI-only expand % I to one file name
% ~ XI-only expand % I to one file extension
% ~ The sI-extended path contains only short names.
% ~ AI-extend % I to file attributes
% ~ TI-extend % I to the date/time of the file
% ~ ZI-expand % I to the file size
% ~ $ PATH: I-find the directory of the environment variable in the PATH and expand % I
The first fully qualified name found. If the environment variable name
Not defined, or the file is not found, this key combination is expanded to an empty string

You can combine modifiers to get multiple results:

% ~ DpI-only expand % I to one drive letter and Path
% ~ NxI-only expand % I to one file name and extension
% ~ FsI-only expand % I to a complete path name with a short name
% ~ Dp $ PATH: I-find the directory of the Environment Variable listed in the PATH and expand % I
To the first drive letter and path.
% ~ FtzaI-extended % I to the DIR similar to the output line

Note: All % ~ The headers are separated by file names or environment variables. To use each item freely, you need to work hard.

Exercise: (I am a little lazy and don't do it myself ...)
Traverse the C and D disks, find known file names (receiving keyboard input), and record the storage location and time to D: \ mynote.txt. The record format is as follows:

The xx files on drive C and drive D are as follows:

Time position

Tip: doscommands, 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. However, this command cannot write batch processing with powerful functions. It is just a doscommand, you need to be familiar with some other DOS commands and the commands provided by Windows systems, and use them in combination to make full use of their powerful and practical functions, so that some complicated things can be processed unexpectedly concise and convenient.

Appendix: A common command or environment setting required in a batch for command:
The for command is actually a loop. If you change the value of an environment variable in each round, in the default state, A for command uses % environment variable % to get the value only once, in the next loop, the previous value (including the execution period of multiple commands in parentheses after do) is changed, and the following command is introduced:
Setlocal enabledelayedexpansion
Start the localization of Environment Changes in the batch file and start the extension of the delayed environment variable. When the execution of SETLOCAL reaches the end of the batch file, an implicit endlocal is executed for each unexecuted setlocal command of the batch file.
When getting the variable value, use! Variable name! The latency environment variable extension allows you to use a different character (Exclamation point) to expand the environment variable during execution. This method is actually applicable to all compound commands in batch processing. If you do not want to retain the changed environment after the batch processing, we recommend that you always add setlocal.
If you combine some other complex system-related and network commands (such as wmic and net), it is the hero of Fang Xian. FOR example, you can use commands to traverse a local disk: wmic logicaldiskwhere "drivetype = 3" get name is obviously easy to find a file in all disks and perform corresponding operations. Using the for command also requires the cooperation of other commands with the computer. Haha, I have a limited level, but I only write a low level... I hope it will be helpful to beginners who are interested in DOS.

DOS for instance

Format: FOR [parameter] % variable name IN (related file or command) Command executed by DO
Purpose: execute specific commands on each object in one or more files, strings, or command results to achieve the desired results.
Note: when using the FOR command in the batch processing file, use % variable instead of % variable to specify the variable. Variable names are case sensitive, so % I is different from % I.
About: The for command can contain or does not contain parameters. The following parameters are supported:/d/l/r/f
The following are two explanations:

===
Zero: No parameter:
---
FOR % variable IN (set) DO command [command-parameters]
% Variable specifies a single letter replaceable parameter.
(Set) specifies one or more files. Wildcard characters can be used.
Command specifies the command executed on each file.
Command-parameters
Specify parameters or command line switches for specific commands.

TTT example:
For % I in (t *. *) do echo % I -- display the file matching t *. * in the current directory (only the file name is displayed, not the path)
For % I in (d: \ mydocuments \ *. doc) do @ echo % I -- display files matching *. doc under the d: \ mydocuments \ directory

===
1. Parameter/d (the parameter can only display the directory name under the current directory)
---
Format: FOR/D % variable IN (set) DO command [command-parameters]
This parameter is mainly used for Directory Search and does not search for files. The/D parameter can only display the directory name under the current directory. (TTT Special Note: Only the directories under the specified directory will be searched, and no more directories at the next level will be searched .)

TTT example:
For/d % I in (c: \ *) do echo % I -- display all directories under the c root directory
For/d % I in (???) Do echo % I -- display a directory with only 1-3 letters in the current directory

===
2. Parameter/R (search for all files matching the set in the specified path and all subdirectories)
---
Format: FOR/R [[drive:] path] % variable IN (set) DO command [command-parameters]
This command searches for the specified path and all files that match the set in all subdirectories. Note that the path and all subdirectories are specified.

1. If the file name in set contains wildcards (? Or *), lists the directory specified by the/R parameter and all the files that match the set in the subdirectories below it, and the directories that do not match the file are not listed.
2. If set is a specific file name without wildcards, enumerate the directory tree (that is, list the Directory and all its subdirectories) (and add the specific file name to the end ), regardless of whether the specified file in the set exists.
Example: for/r c: \ % I in (*. exe) do echo % I -- list the C root directory and all the EXE files under each directory !!!!

TTT example:
For/r c: \ % I in (boot. ini) do echo % I -- enumerate all directories on drive c
For/r d: \ backup % I in (1) do echo % I -- enumeration d \ backup Directory
For/r c: \ % I in (boot. ini) do if exist % I echo % I -- a good search command to list directories in boot. ini

===
3. Parameter/L (this set represents a sequence of numbers from start to end in incremental form. Negative steps can be used)
---
Format: FOR/L % variable IN (start, step, end) DO command [command-parameters]
This set indicates a sequence of numbers from start to end in incremental form. You can use a negative Step.

TTT example:
For/l % I in (1, 1, 5) do @ echo % I -- output 1 2 3 4 5
For/l % I in (, 10) do @ echo % I -- output, 9
For/l % I in (100,-) do @ echo % I -- output, 80, 60, 40, 20
For/l % I in (, 5) do start cmd -- open five CMD windows
For/l % I in (, 5) do md % I -- create from 1 ~ 5. Five folders in total
For/l % I in (1, 1, 5) do rd/q % I -- delete from 1 ~ 5. Five folders in total

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.