Ultimate DOS Batch For loop command detailed _dos/bat

Source: Internet
Author: User
Tags eol extend first string modifier reserved

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

Parameter/F (use file resolution to process command output, string, and file contents.) )
This parameter is the most difficult, the argument is more, first simple explanation: The for command takes this parameter to analyze the file content, the string content or the result of a command output, and by setting option we want the result.
The following is a master's explanation, feeling a little too professional, since I think it is not easy to understand, also listed:
[Iteration and file resolution--use file resolution to process command output, strings, and file contents. Use the iteration variable to define the content or string to check, and further modify the resolution using various options choices. Use the Options token option to specify which tokens should be passed as iteration variables.
Please note that if you do not use the token option,/F will only check the first token. The file resolution process involves reading the output, string, or file contents, dividing it into separate lines of text, and then parsing each row into 0 or more tokens. The For loop is then invoked by the value of the iteration variable set to the token.
By default,/F passes the first blank separator for each row of each file. skipping blank lines. ]
Format:
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]

TTT Note: The above is the WinXP system of Help content, you can notice that the two are exactly the same, this is actually a system error, the second paragraph "If there are USEBACKQ options:" Should be the following content:
for/f ["Options"]%variable in ("File-set") do command [Command-parameters]
for/f ["Options"]%variable in (' String ') does command [Command-parameters]
for/f ["Options"]%variable in (' command ') does command [Command-parameters]--(the quote in ' command ' is an inverted quotation mark, the key to the left of the number 1 on the keyboard)


(TTT Note: The following is a detailed explanation, most of the Help content in the system, but also some errors (no wonder for the order so difficult to learn), has been corrected by me. )
  

1 Option keyword Detailed:
Eol=c: Refers to the end of a line comment character (just one). For example: eol=; --ignore those lines that begin with a semicolon;
Skip=n: Refers to the number of rows ignored at the beginning of the file. For example: skip=2--Ignore 2 lines;
Delims=xxx: Refers to the delimiter set. This replaces the default delimiter set for spaces and tabs. For example: [Delims=,]--Specify a comma, a space to separate the strings.
Tokens=x,y,m-n: refers to which symbol of each line is passed to the for itself of each iteration. This results in an assignment of the extra variable names. The m-n format is a range. Specify MTH by nth symbol. If the last character in the symbol string is an asterisk, then the extra variable is allocated and accepts the reserved text of the row after the last symbol resolution. For example: tokens=2,3*--passes the second and third symbols in each row to the for program body; tokens=2,3* i%--assigns the second string that is fetched to i%, the third to j%, and the rest to k%.
About USEBACKQ, different versions of the system prompts different help, but all contribute to understanding, so all excerpts are as follows:
(1), USEBACKQ: Use the back quotation mark (the key on the keyboard with the number 1 to the left). When parameter USEBACKQ is not used: File-set represents a file and cannot be quoted, so it cannot contain spaces; double quotation marks denote a string, or "string," and a single quotation mark to execute the command, that is, ' command '. When using parameter usebackq: File-set and "File-set" both represent files, which can be enclosed in double quotes when there are spaces in the file path or name; single quotation marks represent strings, that is, ' string '; (This section is help in the WinXP system)
(2), USEBACKQ: Specifies that the new syntax is used in the following cases: A string that executes a post quotation mark as a command, and a single quote character as a literal string command, and allows the file name to be extended in filenameset with double quotes.
The above two combination look, actually already can understand, I explain again:
In fact, the purpose of this parameter is to process file names with spaces. If you are working with a file name and a path that contains spaces, you will be prompted to not find the file if you use it directly. If you enclose the file name and path in double quotes. This is handled as a string instead of as a file. This "USEBACKQ" parameter was added to deal with this situation. If this argument is used, the system can be considered a file for a collection of double quotes in parentheses, a true string with single quotes, and a command to enclose the quotation marks.

2) File-set to one or more file names. Each file is opened, read, and processed before continuing to the next file in File-set. Processing involves reading a file, dividing it into lines of text, and then parsing each row into 0 or more symbols. The For loop is then invoked with the value of the symbol string variable that was found. By default,/F is separated by the first blank symbol in each row of each file. Skips blank lines. You can override the default resolution operation by specifying the optional options argument. This quoted string includes one or more keywords that specify different parsing options.

3)%i: specifically described in the For statement,%j and%k are specifically described through the tokens= option. You can specify up to 26 symbols by tokens= line, as long as you do not attempt to describe a variable above the letter ' z ' or ' z '. Keep in mind that for variables are single letter, case-sensitive, and global, and that no more than 52 are in use at the same time.
(TTT Supplemental Note:
generally after tokens only specify the first parameter, such as%%i or%%a, followed by the second and more than two parameters, automatically in order down. If the previous designation is%%a, then the%%b represents the second result, and the%%c represents the third result ... After testing the tokens to specify multiple variable names, no test success, should not be. So token can only be followed by the first variable name to use
if the variable name used is more than%z or%z, it cannot be used, once thought will cycle over: such as%%z can use%%a or%%a, but after testing, this is not possible.
such as: for/f "tokens=1,2,3* delims=-,"%%y in ("AA bb,cc-dd ee") do echo%%y%%z%%a%%a--only the first two strings are exported, and the following two variables are invalid.
The following are examples provided by the system:
for/f "eol=; tokens=2,3* delims=,%i in (myfile.txt) do @echo%i%j-
Description: Each row in the%k is parsed,
MyFile.txt; --ignore those lines that begin with a semicolon;
Tokens=2,3*-Passes the second and third symbols in each row to the for program body;
delims=,--delimited by commas and/or spaces.
%i--this for-body statement references%i to get the first string (in this case, the second symbol), referencing%j to get the second string (the third symbol in this case) to refer to%k to get all the remaining symbols after the third symbol.
(TTT Description: An obvious error in the above example and description,%i should be replaced with%%i (there is a clear description in the Help: Specify the variable please use%%variable instead of%variable, mislead)

TTT: Here are a few examples I've done:
1, analysis of the file examples
For/f "eol=; tokens=1,2* delims=,-"%%i in (d:\test.txt) do echo%%i%%j%%k
2, an example of an analysis string:
for/f "tokens=1,2,3* delims=-,"%%i in ("AA bb,cc-dd ee") do echo%%i%%j%%k%%l
3, analyze the output of the command example:
for/f "Tokens=1* delims=="%%i in (' Set ') do @echo [%%i----%%J]

If you use the USEBACKQ parameter, the command follows, and the result is exactly the same as above.
1, analysis of the file examples
for/f "Usebackq eol=; tokens=1,2* delims=,-"%%i in" ("D:\test.txt") do echo%%i%%j%%k
2, an example of an analysis string:
for/f "Usebackq tokens=1,2,3* delims=-,"%%i in (' AA bb,cc-dd ee ') do echo%%i%%j%%k%%l
3, analyze the command output example: (Enumerates the environment variable names and values in the current environment). )
for/f "Usebackq tokens=1* delims=="%%i in (' Set ') do @echo [%%i----%%J]
As a result, you can try it, it's easy to understand.

The substitution of the variable
for variable reference in the

for command 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 pathname,
%~di-%I only Expand to a drive letter
%~pi-only%I Extend to a path
%~ni-only%I Expand to a filename
%~xi-only%I Extended to a file name extension
%~si-The extended path contains only short names
%~ai-will%I File properties extended to Files
%~ti-will%I Date/Time extended to file
%~zi-will%I Expands to the size of the file
~ $PATH: I-Find the directory listed in the PATH environment variable (TTT hint: The directory of the Environment variable path) and%I Expands to the first fully qualified name found. If the environment variable name is not defined or the file is not found, the key combination expands to an empty string
In addition, you can combine modifiers to get multiple results:
%~dpi-only%I Expand to a drive letter and path
%~nxi-only%I Expands to a filename and extension
%~FSI-only%I Expand to a full pathname with a short name
%~dp$path:i-Find the directory listed in the PATH environment variable and%I Expands to the first drive letter and path found.
%~ftzai-Will%I DIR
extended to a similar output line in the above example,%I And PATH can be replaced with other valid values. The ~ syntax terminates with a valid for variable name. Select a similar%I Uppercase variable names are easier to read and avoid confusion with key combinations that are not case-insensitive.

(These are the contents of the system help)
We can see that each row has a capital letter "I", which is actually the variable we're bringing in for example:
for/f "Usebackq eol=; tokens=1,2* delims=,-"%%x in" ("D:\test.txt") do echo%%x%%y%%z
Here we are going to change that x,y,z into%~FX,%~FY,%~FZ.

TTT Special case: The following is a comprehensive example of my description, can be copied directly into Notepad, save as a bat format (c disk Next directory), after the operation, you can visually see the effect of the expansion.

@echo off echo---display "dir c:\boot.ini/b/ah" for/f "delims=="%%i in (' dir c:\boot.ini/b/ah ') do echo does not extend variable%%i for/f "delims=="%%i in (' dir c:\boot.ini/b/ah ') do echo extension variable to ~fi%%~fi--extends to a fully qualified pathname for/f "delims=="%%i in (' di R c:\boot.ini/b/ah ') do echo extension variable to ~di%%~di--only the variable is extended to a drive letter for/f "delims=="%%i in (' dir c:\boot.ini/b/ah ') do Ech 
  o Extended variable to ~pi%%~PI--only the variable is extended to a path for/f "delims=="%%i in (' dir c:\boot.ini/b/ah ') do echo extension variable to ~ni%%~ni--only the variable is extended to a filename for/f "delims=="%%i in (' dir c:\boot.ini/b/ah ') do echo extension variable to ~xi%%~xi--only the variable is extended to a file name extension for/f "delims=="%%i in (' dir c:\boot.ini/b/ah ') do echo extension variable to ~si%%~si--The extended path contains only the short name for/f "delims=="%%i in (' dir c:\boot.ini/b/ah ') do EC HO extended variable to ~ai%%~ai--Expands the variable to the file's file attribute for/f "delims=="%%i in (' dir c:\boot.ini/b/ah ') do echo extension variable to ~ti%%~ti--Expands the variable to the file's Date/Time for/f "delims=="%%i in (' dir c:\boot.ini/b/ah ') do echo extension variable to ~zi%%~zi--expands variable to file size for/f "delims=="%%i I N (' dir c:\boot.ini/b/Ah ' do echo extension variable to ~ $PATH: I%%~ $PATH: I--Find the directory listed in the PATH environment variable, and extend the variable to the first fully qualified name echo---The following display combination modifier for multiple results---: for/f "delims = = "%%i in (' dir c:\boot.ini/b/ah ') do echo extension variable to ~dpi%%~dpi--only the variable is extended to a drive letter and path for/f" delims== "%%i in (' dir c:\boot . ini/b/ah ') do echo extension variable to ~nxi%%~nxi--only extend variable to a filename and extension for/f "delims=="%%i in (' dir c:\boot.ini/b/ah ') do echo extension Variable to ~FSI%%~FSI--only the variable is extended to a complete pathname with a short name for/f "delims=="%%i in (' dir c:\boot.ini/b/ah ') do echo extension variable to ~dp$path:i%%~dp$p ATH:I-finds the directory listed in the PATH environment variable and expands the variable to the first drive letter and path found for/f "delims=="%%i in (' dir c:\boot.ini/b/ah ') do echo extension variable to ~ftzai%%~ft
  Zai-The Dir echo that extends the variable to a similar output line. echo---show "dir c:\windows\system32\notepad.exe/b" for/f "delims=="%%i in (' dir c:\windows\system32\notepad.exe/b ') d o echo does not extend variable%%i for/f "delims=="%%i in (' dir c:\windows\system32\notepad.exe/b ') do echo extension variable to ~fi%%~fi--extended to a fully qualified
Path name for/f "delims=="%%i in (' dir c:\windows\system32\notepad.exe/b ') do echo extension variable to ~di%%~di--only the variable is extended to a drive letter  for/f "delims=="%%i in (' dir c:\windows\system32\notepad.exe/b ') do echo extension variable to ~pi%%~PI--only the variable is extended to a path for/f "Delim s== "%%i in (' dir c:\windows\system32\notepad.exe/b ') do echo extension variable to ~ni%%~ni--only the variable is extended to a filename for/f" delims== "%%i in (' Dir c:\windows\system32\notepad.exe/b ') do echo extension variable to ~xi%%~xi--only the variable is extended to a file name extension for/f "delims=="%%i in (' dir C:\WINDO Ws\system32\notepad.exe/b ') do echo extension variable to ~si%%~si--The extended path contains only the short name for/f "delims=="%%i in (' dir C:\WINDOWS\system32\note Pad.exe/b ') do echo extension variable to ~ai%%~ai--Extend variable to file properties for/f "delims=="%%i in (' dir c:\windows\system32\notepad.exe/b ') Do echo extension variable to ~ti%%~ti--date/time to extend variable to file for/f "delims=="%%i in (' dir c:\windows\system32\notepad.exe/b ') do echo extension variable To ~zi%%~zi--Expands the variable to the size of the file for/f "delims=="%%i in (' dir c:\windows\system32\notepad.exe/b ') do echo extension variable to ~ $PATH: I%%~ $P ATH:I--Find the directory listed in the PATH environment variable and extend the variable to the first fully qualified name echo found---The following display the combination modifier to get multiple results---: for/f "delims=="%%i in (' dir C:\WINDOWS\syst Em32\notepad.exe/b ') do echo extension variable to ~dpi%%~dpi--only the variable is extended to a drive letter and path for/f "delims=="%%i in (' dir c:\windows\system32\notepad.exe/b ') do echo extension Variable to ~nxi%%~nxi--only the variable is extended to a filename and extension for/f "delims=="%%i in (' dir c:\windows\system32\notepad.exe/b ') do echo extension variable to ~FSI  %%~FSI--Only the variable is extended to a full pathname with a short name for/f "delims=="%%i in (' dir c:\windows\system32\notepad.exe/b ') do echo extension variable to ~dp$path:i %%~DP$PATH:I-Find the directory listed in the PATH environment variable and extend the variable to the first drive letter and path found for/f "delims=="%%i in (' dir c:\windows\system32\notepad.exe/b ') d o echo Extended variable to ~ftzai%%~ftzai--The Dir Pause that extends the variable to a similar output line


TTT Description:
1, the above command,%%~FSI can not be displayed, is estimated to be a system error, because the%%~FI is extended to a fully qualified pathname,%%~si contains only the name of the short file, itself is contradictory, so error. Do not know is the system error or test US ~ ~
2, the above command cannot display the correct drive and path if it is saved in another disk.
3, if you want to%%~dp$path:i normal display, to ensure that the environment variable path does have this path: C:\WINDOWS\system32.


Here's how:

One, ~i-Remove any quotes ("), Extend%I
The role of this variable as his description, delete quotes!
Remove the quote rule as follows (add!) :
1, if the string at both end of the quotation marks, then delete the end of the quotation marks;
2, if there is no quotation mark at the end of the string, delete the first quotation mark;
3. If there is a quotation mark in the middle of the string, or if there is only quotation marks at the end, it is not deleted.
Tornado added: No head is not deleted, there is a head to delete the tail.

Let's take a look at this example and first create a temporary file temp.txt, which reads
"1111
"2222"
3333 "
"4444" 44
"55" 55 "55
You can also create a bat file code as follows:

@echo off
echo ^ "1111>temp.txt
echo" 2222 ">>temp.txt
echo 3333^" >>temp.txt
echo "44 "44>>temp.txt
echo ^" "55>>temp.txt
rem" To create a temporary file, note that the quotation marks to be separated by the escape character ^, the redirection symbol do not leave blank before
for/f "Delims="%%i in (temp.txt) do echo%%~i
pause
del temp.txt

After execution, we look at the cmd echo as follows:
1111 #字符串前的引号被删除了
2222 #字符串首尾的引号都被删除了
3333 "#字符串前无引号, followed by quotes reserved
4444 "#字符串前面的引号删除了, while the middle of the quotes are reserved
#字符串前面的引号删除了, while the middle quotation marks are reserved
Please press any key to continue ...

In contrast to the previous temp.txt, we'll find that the quotes in lines 1th, 2, and 5 are gone, which is the effect of removing the quotes ~i!
   Second,%~fi-will%I Extend to a fully qualified path name
Example:
Keep the code in any place, I'll put it on the table.
for/f "delims=="%%i in (' dir/b ') do @echo%%~fi
Pause

After execution, the contents are displayed as follows
C:\Documents and settings\administrator\ Desktop \test.bat
C:\Documents and settings\administrator\ Desktop \test.vbs
When I change the%%~fi in the code directly to%%i
for/f "delims=="%%i in (' dir/b ') do @echo%%i
Pause
After execution, the following is displayed:
Test.bat
Test.vbs
By contrast, it is easy to see that there is no path, which is "to%I Extended to a fully qualified pathname "the role, that is, if the content of the%i variable is a filename, he will be the absolute path of the file to print out, rather than just print a file name, the hands-on experiment you know!
   Third,%~di-only will%I Extend to a drive letter
See Example:
The code is as follows, I still put on the desktop execution!
for/f "delims=="%%i in (' dir/b ') do @echo%%~di
Pause
After execution I cmd shows the following
C:
C:
My desktop is two files Test.bat,test.vbs,%%~di function is, if the variable%%i content is a file or directory name, he will be his file or directory of the disk symbol printed out!

   Iv.%~pi-Only%I Extend to a path
This usage is the same as above, he only prints the path does not print the file name
for/f "delims=="%%i in (' dir/b ') do @echo%%~pi
Pause
I will not hit the results, we copy the code to see the results, the following are a few of the use of the code to come out, we see the results!

   V.%~ni-will only%I Extend to a filename
Print file names only
for/f "delims=="%%i in (' dir/b ') do @echo%%~ni
Pause

   Vi.%~xi-Will%I only Extend to a file name extension
Print only the extension of a file
for/f "delims=="%%i in (' dir/b ') do @echo%%~xi
Pause

   Vii.%~si-extended paths contain only short names
Print absolute Short file name
for/f "delims=="%%i in (' dir/b ') do @echo%%~si
Pause

   Eight,%~ai-will%I File attributes extended to files
Print the properties of a file
for/f "delims=="%%i in (' dir/b ') do @echo%%~ai
Pause

   Ix.%~ti-Will%I Date/time of extension to file
Print the date the file was created
for/f "delims=="%%i in (' dir/b ') do @echo%%~ti
Pause

   Ten,%~zi-will%I Size of file extended to
Size of the print file
for/f "delims=="%%i in (' dir/b ') do @echo%%~zi
Pause
Tornado Supplement: The above example "delims==" can be changed to "delims=", that is, do not separator

   Xi. ~ $PATH: I-Find the directory listed in the PATH environment variable, and%I Expands to the first fully qualified name found. If the environment variable name is not defined, or if the file is not found, the key combination expands to an empty string
This is the last one, and it's not the same, I said alone!
Then save the code as a batch and put it on the desktop.
@echo off
for/f "delims="%%i in ("notepad.exe") do echo%%~ $PATH: I
Pause
Tornado Supplement: The above code shows the result as C:\WINDOWS\system32\notepad.exe
He meant to search for notepad.exe files in the path specified in the path variable, and if Notepad.exe would print out his absolute path, print a mistake!
(TTT description, saved to the desktop, run the result is: The system cannot find the file "notepad.exe".) View environment Variables There is indeed this path in path, unknown cause! Later discovered, the original is the reason of Chinese quotation marks.
The above command should be written as:
for/f "delims="%%i in ("notepad.exe") do echo%%~ $PATH: I
)
Finally send a batch processing to do a Gobang game can refer to the following article

Http://www.jb51.net/article/29885.htm

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.