DOS command for usage detailed _dos/bat

Source: Internet
Author: User
Tags eol extend lowercase modifiers first row
For help document

Executes a specific command on each file in a set of files.

For%variable in (set) do command [Command-parameters]

%variable specifies a single letter replaceable parameter.
(set) to specify one or a set of files. You can use wildcard characters.
command specifies the commands that are executed for each file.
Command-parameters
Specify a parameter or command-line switch for a specific command.

When you use the for command in a batch program, specify the variable using the%%variable
Instead of using%variable. Variable names are case-sensitive, so%i are different from%i.

If command extensions are enabled, the following additional for command formats are
Support:

FOR/D%variable in (set) do command [Command-parameters]

If the set contains wildcard characters, specify a match to the directory name, not the file
Name match.

FOR/R [[Drive:]path]%variable in (set) do command [Command-parameters]

Check the [drive:]path-rooted directory tree, pointing to the
The For statement. If no directory is specified after/R, the current
Directory. If the set is only one single point (.) character, the directory tree is enumerated.

FOR/L%variable in (start,step,end) do command [Command-parameters]

The set represents a sequence of numbers in increments from start to finish.
Therefore, (1,1,5) will produce a sequence of 1 2 3 4 5, (5,-1,1) will produce
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 you have the USEBACKQ option:

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 the filenameset.
Before the next file, each file has been opened, read, and processed.
Processing involves reading a file, dividing it into lines of text, and then each row
resolves to 0 or more symbols. Then use the found symbol string variable value
Call the For loop. By default,/F is separated from each row of each file
The first blank symbol. Skips blank lines. You can specify optional "options" by specifying
Parameter overrides the default resolution operation. This quoted string consists of one or more
Specifies keywords for different resolution options. The key words are:

Eol=c-refers to the end of a line comment character (just one)
Skip=n-refers to the number of rows ignored at the start of the file.
Delims=xxx-refers to the delimiter set. This replaces the space and the jump bar
The default delimiter set.
Tokens=x,y,m-n-refers to which symbol of each line is passed to each iteration
For itself. This results in an assignment of the extra variable names. M-n
Format is a range. Specify MTH by nth symbol. If
The last character in the symbol string, asterisk,
Then the extra variables will be followed by the last symbol resolution
Assign and accept the reserved text for the line.
USEBACKQ-Specifies that the new syntax is already used in the following class cases:
Executes a string of post quotes as a command and a single
The quote character is a literal string command and is allowed in the FileNameSet
Use double quotes to expand the file name.

Some examples may help:

For/f "eol=; tokens=2,3* delims=, "%i in (myfile.txt) do @echo%i%j

Each row in the myfile.txt is parsed, and those lines that begin with a semicolon are ignored, and the
The second and third symbols in each row are passed to the for program body, with commas and/or
Space-delimited symbol. Note that the statement for the body of this for program references%i to
Get the second symbol, refer to%j to get the third symbol, and reference the%k
To get all the remaining symbols after the third symbol. For a file with spaces
Name, you need to enclose the file name in double quotes. In order to make it in this way
With double quotes, you also need to use the USEBACKQ option, otherwise the double quotes will
is understood to be used to define a string to parse.

%i is specifically described in the For statement,%j and%k are
The tokens= option is specifically described. You can use the tokens= line
Specify up to 26 symbols, as long as you do not attempt to describe an above-letter ' Z ' or
Variable of ' Z '. Keep in mind that the for variable is single letter, case, and global;
No more than 52 are in use at the same time.

You can also use for/f parsing logic on adjacent strings;
Enclose the filenameset between parentheses in single quotes. In this way, the character
The string is treated as a single input line in a file.

Finally, you can use the for/f command to parse the output of the command. The method is to
The filenameset between parentheses becomes a reverse-enclosed string. The string will
is passed to a child CMD as a command line. EXE, whose output will be caught in
Memory and is treated as a file analysis. Therefore, the following example:

for/f "Usebackq delims=="%i in (' Set ') do @echo%i

The name of the environment variable in the current environment is enumerated.

In addition, the substitution of a for variable reference has been enhanced. You can now use the following
Option syntax:

~i-Remove any quotes ("), Extend%I
%~fi-Will%I Extend to a fully qualified path name
%~di-Will%I only Extend to a drive letter
%~PI-Will%I only Extend to a path
%~ni-Will%I only Extend to a filename
%~xi-Will%I only Extend to a file name extension
%~si-The path to the extension contains only the short name
%~ai-Will%I File attributes extended to files
%~ti-Will%I Date/time of extension to file
%~zi-Will%I Size of file extended to
~ $PATH: I-Find directories listed in PATH environment variables, and%I Extended
To the first fully qualified name found. If the environment variable name
is not defined, or the file is not found, this key combination expands to the
Empty string

You can combine modifiers to get multiple results:

%~DPI-Will%I only Extend to a drive letter and path
%~nxi-Will%I only Extended to a file name and extension
%~FSI-Will%I only Extend to a full pathname with a short name
%~DP$PATH:I-Searches the directories listed in the PATH environment variable and will%I Extended
To the first drive letter and path found.
%~ftzai-Will%I DIR extending to a similar output line

In the above example,%I And PATH can be replaced with other valid values. ~ Grammar
Terminates with a valid for variable name. Select a similar%I The uppercase variable name
It is easier to read and avoids confusion with key combinations that are not case-sensitive.

the use of for in DOS

For/parameter% variable in (set) do command
For four kinds of parameters D L R F

I. Parameter/d
For/d% variable in (set) do command
The/d parameter is a for command that specifies only the execution of the directory, not the file.

Ii. parameter/R
The/R parameter can also be followed by a drive letter and path
FOR/R Here you can have the path% variable in (set) do command
The path after/R refers to all directories in the entire directory tree below it, equivalent to the range in DOS command trees, if it is only an English period. , refers to the directory tree under the current path, which is referred to as the current directory if the path is omitted, and the subsequent in (set) corresponds to the set of files that match each previous directory
There are two cases where there are no wildcard characters in the in (set)
1) in (set) no wildcard characters
Specifies a single file or enumeration of specific files (multiple file names separated by delimiters, such as spaces, commas, etc.)
Example 2
@echo of
For/r. %i in (abc.txt) do echo. >%i
echo on
Note: There is only one path after the for/r. And the echo in each loop behind it. >%i is equivalent to creating a text file with only a blank line, the overall effect is to include a subdirectory in the current directory, and a abc.txt in each directory.
Example 3 (Put in batch)
@echo off
REM Displays a list of all file names File1 and File2 on the D: disk
FOR/R d:\%%h in (file1,file2) do if exist%%h echo%%h
Pause
2) in (set) contains wildcard characters * or?
This kind of do command will process each item in the directory series that is specified in the previous/R, containing the files in the in (set), without ignoring those directories that do not contain matching files
Example 4:
@echo off
REM Deletes all *.chk files in C disk
FOR/R C:\%%h in (*.chk) do del/q%%h
Pause
Note: del/q means delete in quiet mode (no confirmation required)
Iii. Parameters/L
for/l%% variable in (starting value, each increment, the comparison value at the end) do command
(Upper L can also be lowercase, mainly to visually not be confused with the number 1 without lowercase)
(starting value, each increment, the end of the comparison value) is equivalent to a series of linear numbers, from the start value number, each increment (or set to negative) is added each time and is compared to the compare at end, which exits the For loop (nor does the do command after this round).
For example (1,1,3) will produce a sequence (1 2 3); (1,2,9) will produce a sequence (1 3 5 7 9); (5,-1,1) will produce a sequence (5 4 3 2 1); (1,3,18) will produce a sequence (1 7 10 13 16)
Example 5
@echooff
:: Set up aa1~ aa5 five folders in D disk
For/l%%i in (1,1,5) do MD d:\aa%%i
Pause

Note: At the beginning of the line, a single colon: followed by the name, is the label row, corresponds to the position pointed to after the go in the batch, and the double colon:: Generally used for annotations, notes can be expressed with REM plus space in batches, and the REM annotation appears on the screen when the command echo is not closed, and: is not displayed under any circumstances.

Iv. parameter/F
This parameter/f will open the file in the (set), so that the for command can handle the reading of text files and add delete replacement and other editorial operations, is powerful and therefore relatively complex.
FileName-Set
for/f "Options"% variable in ("string"-set) do command
' Command '-set
/F can be followed by several options, without the option is also a qualified format, and with parameters must be enclosed in quotation marks, followed by the set mainly in three forms, and eventually in the for loop in each round will be formed to read a line of strings, to give the specified% variable, And to assign a value to an additional variable due to an option, execute the command after do
The following examples illustrate and progressively understand the use of the sub-items
Example 6
Suppose the D:\abc.txt content is as follows:
Name Sex Age ETC-Class
John Male A-1
Lee four male B-2

Zhaoliu A-2

Execute the following command:
for/f%c in (d:\abc.txt) do @echo%c
The screen displays:
Name
Tom
John doe
Zhao Liu

Explanation: This is the case when the default parameter option is FOR/R before "% variable". Each round of the loop is delimited by a space, dividing the string by line in the open file, and because no additional variable (that is, only one variable%c) is added to the assignments, the first paragraph is only given to%c, followed by the Do command. Then loop the next round and ignore the blank line by default
Change:
for/f "Skip=1 tokens=1,4 delims="%c in (d:\abc.txt) do @echo%c%d
Display as:
John A-1
Dick B-2
Zhao Liu A-2

Solution:
Skip=1 indicates that the number of lines that the text starts to ignore is 1--ignore several lines
Delims= on one line, with what single symbol (can have multiple character combinations, there is also no space between, understood as a number of individual characters, such as spaces to be put the last to separate the string as the reading of the Assigned unit (form a paragraph), in this case, after the equals sign is empty representation only separated by space. --with what knife to slice
tokens=1,4 this equals sign, followed by a number of delimited string segments, respectively assigned to the% variable and the sequence of additional variables, this example takes the 1th paragraph to the%c, the 4th paragraph assigned to the C after a variable that is assigned to%d, and can be written as tokens= The 1,2,5-7 or tokens=1,2,3* or tokens=1,2,5,7 respectively represents the 1,2,5,6,7 (assigned to%c,%d,%e,%,f,%g altogether 5 variables), 1,2,3, and all segments after 3 (to 3 variables), 1,2,5,7 ( To assign to 4 variables, the number numbers can be tokens=, but the order of writing corresponds to the order in which the variables are assigned, which is an assignment, and it's not a different thing to do after the do command. In other words--at most, you need to take a few paragraphs
In (variable) of the variable, which represents the beginning of a variable name, according to the total number defined in tokens to expand the additional variable name, if the total number is 3, then%c append%d and%e, if%c is attached%d%e ... In this case, there are only two tokens=1,4, the first paragraph in the in () bracket is assigned to%c, and the 4th paragraph is assigned to the variable%d
Take the second line (the first row has been skipped by Skip=1) For example, in the "Zhang Three male A-1" (exactly is the space separated) by the space knife cut to five paragraphs, as long as the 1th, 4, that is, Zhang Sanxi to%c, A-1 assigned to%d, execute @echo%c%d then next round ... And the empty line is omitted as usual.

Just a little change:

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

is displayed as:
A John
B Dick
A Zhao Liu

Example 7
Suppose the D:\aa.txt content 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

At the command line, enter:
for/f "Skip=5 tokens=5"%a in (d:\aa.txt) do @echo%a
will display:
Yg0925.txt
Buple.txt
Vitn.txt
Free

Intended to display files listed in the file (of course, can also be replaced by other commands to the file operation)
Ignoring the first 5 lines through skip=5, the default is separated by a space after tokens=5 fetch the fifth paragraph of each line to the file name to the variable%a, the last line to take a file is not a filename (of course, other methods can be used to deal with this superfluous only for/f in the last few lines do not provide the format), And the penultimate line has no fifth paragraph.
Obviously, the contents of the Aa.txt in the example are the contents of the dir command once executed. It can be similar to a command:
Dir >d:\aa.txt to build
On the other hand, if you add the appropriate parameters in Dir/b, you can avoid the redundant parts, you can also join/ad only show directories, add/a-d only show files, etc.
So, we can simply write the commands into the in (' Command '-set)
for/f "Skip=5 tokens=5"%a in (' dir ') do @echo%a

Effect.
Note: The command set needs to be enclosed in single quotes to indicate that it is not a set of files, which, in double quotes, is a set of strings, in this case, to illustrate the use of the for command, and is willing to use the previous "digression" approach. If you do not show anything after the execution of this example, you need to first execute the command in the set first, look at the format it shows, perhaps you need to change the tokens=5 to tokens=4 maybe you should also add the parameters to dir/a-d to avoid displaying the directory.
If the set is composed of multiple files, then processing one file and then processing another file, the number of rows per file is different cycles (the number of DO commands) will also be different.
If the set is a system generated by the command, then you must first familiarize yourself with the character system in which the command is executed, so that you can properly arrange the following do command

The finishing touch: Regardless of the form in which the set is in, for/f are eventually decomposed into strings, as needed whether to "ignore a few lines" (skip=), "What Knife to Split" (delims=), "the most need to take a few paragraphs" (tokens=) to the set of strings, paragraph by line to the% or% The variables after the% and the variables that may be extended out to execute the DO command, each row is a round loop. All parameters are not fully described here, please use for/at the command line. (The italic text below is the content of the copied help)
For example:
For file names with spaces, you need to enclose the file name in double quotes. In order to use double quotes in this way, you also need to use the USEBACKQ option, otherwise the double quotes are interpreted as being used to define a string to parse. In other words, the USEBACKQ (in the quotation mark after for/f) is still a filename in double quotes in ().
There is also an option eol=: Previously said skip= is to ignore the beginning of a few lines, in fact, the default condition also ignores all semicolons "; "Start the line, if you want to not ignore the beginning of the semicolon line, or you want to ignore the start of the line you specified a character can be used in the quotation mark after the for/f of the eol= you define the character, but it is not as delims= as the definition of multiple, only allowed to define one.

Another pattern: You can use the ~ operator to separate the file name into a file name, extension, disk character, and other independent parts, see the interpretation in for/(where the sample variable is%i):
In addition, the substitution of a for variable reference has been enhanced. You can now use the following option syntax:

~i-Remove any quotes ("), expand%I
%~fi-Will%I Extend to a fully qualified path name
%~di-Will%I only Expand to a drive letter
%~PI-Will%I only Extend to a path
%~ni-Will%I only Extend to a filename
%~xi-Will%I only Extended to a file name extension
%~si-The extended path contains only short names
%~ai-Will%I File attributes extended to files
%~ti-Will%I Date/time of expansion to file
%~zi-Will%I Expand to the size of the file
~ $PATH: I find the directory listed in the PATH environment variable and will%I Expand
To the first fully qualified name found. If the environment variable name
is not defined, or the file is not found, this key combination expands to an empty string

You can combine modifiers to get multiple results:

%~DPI-Will%I only Extend to a drive letter and path
%~nxi-Will%I only extended to a filename and extension
%~FSI-Will%I only Extended to a full pathname with a short name
%~dp$path:i-finds the directory listed in the PATH environment variable and%I Expand
To the first drive letter and path found.
%~ftzai-will%I DIR extended to a similar output line

denoted: the operator of the All-~ is the separate operation of the filename or environment variable. And each one wants to use freely, then need to pay hard practice.

Practice: (I steal a little lazy, I do not do ...)
Traverse C, D disk, find known filename (receive keyboard input), put it in place, time, record to D:\mynote.txt record format such as:

XX year xx month xx Nikkei find in C disk, D disk xx files are as follows:

Time position

Hint: Possible DOS commands, variables, parameters: Echo, set, set/p,%date%,% >, >>

Summary and tips:
The actual usage of the for command is essentially terminated, but this is not the ability to write a powerful batch, it is just a DOS command, need to be proficient in some other DOS commands and Windows system provided by the command, combined to fully develop its powerful, practical functions, so that some complex things, It's surprisingly simple and convenient to handle.

Attachment: A command that is commonly required in a batch for command or is called an environment setting:
The for command is actually a loop, and if you change the value of an environment variable in each round of commands, in the default state, a for command takes only one value per% of the environment variable, then the next round of the cycle or the value before the change (including the execution of the multiple commands in parentheses after do) does not achieve the intended purpose. To do this, introduce the following command:
Setlocal enabledelayedexpansion
Start localized operations for environment changes in batch files and start delaying environment variable extensions. When execution setlocal reaches the end of a batch file, an implied endlocal is executed for each setlocal command that has not yet been executed for that batch file.
When you take the variable value, you use the! Variable name! You can dynamically take values, delay environment variable expansion allows you to use a different character (exclamation point) to expand the environment variable at execution time. This usage actually belongs to the attention of all compound commands in the batch process. If you do not want to keep the changed environment after the batch is finished, the recommendation always adds Setlocal.
If the combination of some other complex system-related, network commands (such as WMIC, net) come in, that is to display for the hero, such as traversing the local disk can be used to command: WMIC logicaldiskwhere "drivetype=3" Get Name Obviously it's easy to find a file on all the disks and do it appropriately, and a good for command requires other commands and a computer base to work with. Oh, my level is limited, write just low-level level ... I hope to be able to come here to see the beginner dos for the command to help.

DOS for instance

Format: for [parameter]% variable name in (related file or command) do execution command
Function: Executes specific commands on one or a set of files, strings, or on each object in the result of a command to achieve the desired result.
Note: When using the for command in a batch file, use%%variable instead of%variable when you specify the variable. Variable names are case-sensitive, so%i are different from%i.
About: The for command can take parameters with or without arguments, with parameters supported by the following parameters:/D/L/r/f
Explain the following separately

===
0: No parameters:
---
For%variable in (set) do command [Command-parameters]
%variable specifies a single letter replaceable parameter.
(set) to specify one or a set of files. You can use wildcard characters.
command specifies the commands that are executed for each file.
Command-parameters
Specify a parameter or command-line switch for a specific command.

TTT Example:
For%%i in (t*.*) do echo%%i--Displays files that match t*.* in the current directory (only the file name is displayed, not the path)
For%%i in (d:\mydocuments\*.doc) do @echo%%i--Displays files that match *.doc under D:\mydocuments\ directory

===
One, parameter/d (parameters can only display the directory name under the current directory)
---
Format: for/d%variable in (set) do command [Command-parameters]
This parameter is used primarily for directory searches, does not search for files, and the/d parameter can only display directory names under the current directory. (TTT Special Note: Only the directories under the specified directory will be searched, and the next level of directories will not be searched.) )

TTT Example:
FOR/D%%i in (c:\*) do echo%%i--Show all directories under C-Packing directory
FOR/D%%i in (???) do echo%%i--Displays a directory with a 1-3-letter name in the current directory

===
Parameter/R (searches for all files in the specified path and in all subdirectories that match the set)
---
Format: FOR/R [[Drive:]path]%variable in (set) do command [Command-parameters]
This command searches for all files in the specified path and in all subdirectories that match the set, noting that the path and all subdirectories are specified.

1, the file name in the set if it contains wildcard characters (?) or *), enumerates all files in the directory specified by the/R parameter and the following subdirectories that match the set, and directories without matching files are not enumerated.
2. If the set contains a specific file name and does not contain a wildcard character, enumerate the tree (that is, enumerate the directory and all subdirectories below it) (with a specific file name followed), regardless of whether the specified file exists in the set.
Example: for/r c:\%%i in (*.exe) do echo%%i--The C-packing directory, and subdirectories of each directory, all of the following EXE files are listed!!!!

TTT Example:
FOR/R C:\%%i in (boot.ini) do echo%%i--Enumerates all directories in C disk
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--Good search command, listing boot.ini existing directory

===
Parameter/L (the set represents a sequence of numbers in increments from start to finish.) You can use a negative step)
---
Format: for/l%variable in (start,step,end) do command [Command-parameters]
The set represents a sequence of numbers in increments from start to finish. 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 (1,2,10) do @echo%%i-Output 1,3,5,7,9
FOR/L%%i in (100,-20,1) do @echo%%i-Output 100,80,60,40,20
FOR/L%%i in (1,1,5) do start cmd--open 5 cmd windows
FOR/L%%i in (1,1,5) do MD%%i--set up from 1~5 total 5 folders
  FOR/L%%i in (1,1,5) do rd/q%%i--delete from 1~5 a total of 5 folders

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.