DOS Batch command for loop command detailed _dos/bat

Source: Internet
Author: User
Tags eol extend lowercase first row

The for command is a command line or batch operation that iterates through a series of objects, running in a command row or in batches, combining some of the programs in Windows Management with a powerful, flexible application that is impressive. However, the complexity of its help information is often daunting to beginners, here according to my understanding of learning, the use of decomposition simplification, negligence and error may be unavoidable.

Basic format

(here is the format used in the command line, if in the batch, you need to add more%%):

For/parameter% variable in (set) do command

(Note: Above except Chinese, the rest is written according to its format, the case is all right)
Parameters: For four parameters D L R F, and some of the parameters can also be attached to the other options below will be described separately
Variables: (Remember that if you use the for command in a batch,% before the variable must be%) The variable name is made up of a single letter and is case-sensitive (as the original help says, the actual use of a single number as a variable name has proved to be feasible), as%b and%b represent different variables.
The for command assigns the value read in the in (set) to this variable in each loop, so that it is referenced in subsequent commands.
Set: A collection of series files, strings, or content produced by a command (available wildcard characters *?) , and can also refer to environment variables), the for command reads the contents of the set in a certain order and regularity, assigns it to the variable, executes the Do command, loops the next round until the contents of the set are read, and the parentheses are in the form (with spaces between the parentheses).
Command: Can be any qualified DOS command or externally callable program, and parentheses can be used to enclose multiple commands in a single loop.
Note: Because some directories or filenames may have spaces, so many times the set and the commands often need to be enclosed in English quotes (but sometimes the quotes may be thought to be strings) to represent a whole, and in some of the examples below, it is simple to ignore the case of a filename or a space with a directory name.
Now give an example of how to use the parameter classification:

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.
Example 1:
Input at the command line (not in batches, no longer explained)
for/d%a in (c:\*.*) do echo%a
The operation will display all the directories in the C-packing directory, without displaying the file name
Looks a bit messy, if the command prompt back to the close is clear:
for/d%a in (c:\*.*) do @echo%a


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) doing 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 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 Delete all *.chk files in C disk
for/r C:\%%h in (*.chk) do del/q%%h


Note: del/q means delete in quiet mode (no confirmation required)

Iii. Parameters/L
For/l% percent 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

@echo off
:: Set up aa1~ aa5 five folders in D disk
for/l%%i in (1,1,5) do MD d:\aa%%i


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 first paragraph assignments to%c, and then the Do command is executed. , and then loop the next round, and ignore blank lines by default
change:
for/f "Skip=1 tokens=1,4 delims="%c in (d:\abc.txt) do @echo%c%d
appears as:
John- 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=1,2,5-7 or tokens=1,2,3* or tokens=1,2,5,7, respectively, for 1,2,5,6,7 (assigned to%c,%d,%e,%,f,%g a total of 5 variables), 1,2,3, and all segments after 3 (to 3 variables), 1,2,5,7 (to be assigned to 4 variables), The number numbers after the tokens= may not be in order, but the order of the writing corresponds to the order in which the variables are assigned, which is assigned, and it is not another matter to use the Do command later. In other words--—— the maximum number of paragraphs you need to take
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 directories listed in PATH environment variables, and%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.

Attached: 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 the command for each round, 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 do after the execution of multiple commands in parentheses), did not achieve the intended purpose, to do so, 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 value of a variable, 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 you combine some other complex system-related commands (such as WMIC, net) to come in, that is to show for the true color, such as traversing the local disk can use the command: WMIC logicaldisk where "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.

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.