Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of for Loop Command for dos batch processing

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you the "dos batch for loop command example analysis", the content is easy to understand, well-organized, hope to help you solve your doubts, the following let Xiaobian lead you to study and learn "dos batch for loop command example analysis" this article.

Format: FOR [parameters]%% variable name IN (related files or commands) commands executed by DO

Function: execute a specific command on each object in a file or set of files, strings, or command results to achieve the desired results.

Note: when using the FOR command in a batch file, specify variables using% variable instead of% variable. Variable names are case-sensitive, so% I is different from% I.

About: the for command can be with or without parameters, and the following parameters are supported with parameters: / d / l / r / f

Let's explain it separately.

Zero: when no parameter:

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

% variable specifies a parameter that can be replaced by a single letter.

(set) specify a file or group of files. You can use wildcards.

Command specifies the commands to be executed on each file.

Command-parameters

Specify parameters or command line switches for a specific command.

TTT example:

For% I in (twee.*) do echo% I-displays the files in the current directory that match twee.* (only the file name, not the path)

For% I in (d:\ mydocuments\ * .doc) do @ echo% I-displays files that match * .doc in the d:\ mydocuments\ directory

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, not for files, and the / D parameter can only display the directory name under the current directory. (TTT special note: only the directory under the specified directory will be searched, not the directory at the next level.)

TTT example:

For / d% I in (c:\ *) do echo% I-- shows all directories under the root directory of disk c

For / d% I in Do echo% I-shows directories with names of only 1-3 letters in the current directory

Parameter / R (search for all files in the specified path and all subdirectories that match set)

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

This command searches for all files in the specified path and all subdirectories that match set, note that the specified path and all subdirectories.

1. If the file name in set contains a wildcard character (? Or *), enumerate all files that match set in the directory specified by the / R parameter and its subdirectories below, and directories without matching files are not enumerated.

2. If the set is a specific file name and does not contain wildcards, enumerate the directory tree (that is, enumerate the directory and all the subdirectories below it) (followed by a specific file name), regardless of whether the specified file in set exists or not.

Example: for / r c:\% I in (* .exe) do echo% I-- list the root directory of C disk and all the EXE files under the subdirectories of each directory!

TTT example:

For / r c:\% I in (boot.ini) do echo%% I-enumerates all directories on disk c

For / r d:\ backup% I in (1) do echo% I-enumerate d\ backup directories

For / r c:\% I in (boot.ini) do if exist%% I echo%% I-- good search command to list the directories where boot.ini exists

Parameter / L (this set represents a sequence of numbers from beginning to end in increments. You can use a negative Step)

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

This set represents a sequence of numbers from beginning to end in increments. You can use negative Step

TTT example:

For / l% I in do @ echo% I-output 1 2 3 4 5

For / l% I in (1meme 2meme 10) do @ echo% I-output 1meme 3meme 5jingle 7meme 9

For / l% I in do @ echo% I-- output 100J 80L 60L 40L 20

For / l% I in (1 CMD 1) do start cmd-open 5 CMD windows

For / l% I in do md% I-create a total of 5 folders from 1 to 5

For / l% I in do rd / Q% I-delete 5 folders from 1pm 5

Parameter / F (use file parsing to handle command output, strings, and file contents.)

This parameter is the most difficult, there are many parameters, first simple explanation: for command with this parameter can analyze the contents of the file, string contents or the results of a command output, and by setting option to get the results we want.

The following is a master's explanation, feeling a little too professional, think it is not easy to understand, also list:

[iteration and file parsing-use file parsing to process command output, strings, and file contents. Use iterative variables to define the content or string to check, and use various options options to further modify the parsing. Use the options token option to specify which tokens should be passed as iteration variables.

Note that when there is no token option, / F will only check the first token. The file parsing process involves reading the output, string, or file contents, dividing it into separate lines of text, and parsing each line into zero or more tokens. The for loop is then called by setting the value of the iteration variable to the token.

By default, / F passes the first white space delimiter on each line of each file. Skip 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 description: the above is the help content in the WinXP system, you can notice that the two are exactly the same, this is actually the system error, the second paragraph "if there is a usebackq option:" should be the following:

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]-(the quotation marks in `command` are backquotes, the key to the left of the number 1 on the keyboard)

1) detailed description of OPTION keyword:

Eol=c: refers to the end of a line comment character (just one). For example: eol=;-ignore lines that start with a semicolon

Skip=n: the number of lines 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 of spaces and tabbed keys. For example: [delims=,]-- specifies that strings are separated by commas and spaces.

Tokens=x,y,m-n: refers to which symbol of each line is passed to the for itself of each iteration. This results in the allocation of additional variable names. The mmurn format is a range. Specify the mth through the nth symbol. If the last character in the symbol string is an asterisk, the additional variable is assigned and accepts the reserved text of the line after the last symbol is parsed. For example: tokens=2,3*-- passes the second and third symbols in each line to the for program body; tokens=2,3*. I%-the second string will be assigned to I%, the third to j%, and the rest to k%.

With regard to usebackq, different versions of the system prompt for different help, but they are all helpful for understanding, so excerpts are as follows:

(1), usebackq: use the quotation marks (the key to the left of the number 1 on the keyboard `). When the parameter usebackq is not used: file-set represents the file and cannot be enclosed in quotation marks, so it cannot contain spaces; double quotation marks indicate the string, that is, "string"; and single quotation marks indicate the execution of the command, that is, 'command'. When using the parameter usebackq: both file-set and "file-set" denote the file, which can be enclosed in double quotation marks when there is a space in the file path or name; single quotation marks indicate a string, that is, the quotation marks after the 'string'; indicate command execution, that is, `command`. (this section is the help in the WinXP system)

(2), usebackq: specifies that the new syntax has been used in the following cases: a string that executes a trailing quotation mark as a command; and a single quotation mark character is a text string command; and allows the file name to be expanded with double quotes in filenameset.

If we look at the combination of the above two items, we can already understand it. Let me explain it again:

In fact, the purpose of this parameter is to deal with file names with spaces. If you are dealing with a file name and path that contains spaces, if you use it directly, you will be prompted that the file cannot be found. If you enclose the file name and path in double quotation marks. This time it will be treated as a string, not as a file. In order to deal with this situation, this "usebackq" parameter is added. If this parameter is used, the system can be considered a file for the collection of double quotes in parentheses; the real string is in single quotes; and the command is in backquotes.

2) file-set is one or more file names. Each file is opened, read, and processed before moving on to the next file in file-set. Processing involves reading the file, dividing it into lines of text, and then parsing each line into zero or more symbols. The For loop is then called with the value of the character string variable found. By default, / F passes through the first white space symbol separated in each line of each file. Skip the blank line. You can override the default parsing operation by specifying the optional "options" parameter. This quoted string includes one or more keywords that specify different parsing options.

3)% I: specifically specified in the for statement, and% j and% k are specifically explained through the tokens= option. You can specify up to 26 symbols on a tokens= line, as long as you don't try to specify a variable higher than the letter'z'or'Z'. Keep in mind that FOR variables are single-letter, case-sensitive, and global; and you can't have more than 52 in use at the same time.

(TTT added:

Generally, only the first parameter, such as% I or% a, is specified after tokens, followed by the second or more parameters, which can be arranged down automatically in order. For example,% an is specified before, followed by% b for the second result and% c for the third result. After testing the tokens, you can specify multiple variable names. If the test is not successful, it should not be allowed. So token can only be followed by the first variable name to be used.

If you use a variable name that exceeds% z or% Z, you can't use it. I thought it would cycle through: for example,% an or% A can be used after% z, but after testing, this is not allowed.

For example: 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 output, and the last 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% k--

Description: each line in the myfile.txt is analyzed

Eol=;-ignore lines that start with a semicolon

Tokens=2,3*-pass the second and third symbols in each line to the for program body

Delims=,-- delimit symbols with commas and / or spaces.

% I-- the statement in this for body refers to% I to get the first string (the second symbol in this case) and% j to get the second string (the third symbol in this case) refers to% k to get all the remaining symbols after the third symbol.

(TTT description: for the obvious errors in the above examples and instructions,% I should be replaced with% I (it is clearly stated in the help: please use% variable for specified variables instead of% variable, misleading)

TTT: here are a few examples I've done:

1. Analyze an example of a file

FOR / F "eol=; tokens=1,2* delims=,-"% I in (d:\ test.txt) do echo% I% j% k

2. Analyze an example of a string:

For / f "tokens=1,2,3* delims=-," I in ("aa bb,cc-dd ee") do echo I j k l

3. Analyze an example of command output:

FOR / F "tokens=1* delims=="%% I IN ('set') DO @ echo [%% I Murray% j]

If you use the usebackq parameter, the command is as follows, and the result is exactly the same as above.

1. Analyze an example of a file

FOR / F "usebackq eol=; tokens=1,2* delims=,-"% I in ("d:\ test.txt") do echo% I% j% k

2. Analyze an example of a string:

For / f "usebackq tokens=1,2,3* delims=-," I in ('aa bb,cc-dd ee') do echo I j k l

3. An example of analyzing the output of the command: (enumerates the names and values of environment variables in the current environment.)

FOR / F "usebackq tokens=1* delims=="% I IN (`set`) DO @ echo [%% I Murray% j]

As a result, you can try it, and it's easy to understand.

Variables in the FOR command

The replacement of FOR variable references has been enhanced. You can now use the following option syntax:

~ I-remove any quotation marks ("), expand% I

% ~ fI-extends% I to a fully qualified pathname

% ~ dI-expand% I to only one drive letter

% ~ pI-extends% I to only one path

% ~ nI-extends% I to only one file name

% ~ xI-extends% I to only one file extension

% ~ sI-the extended path contains only short names

% ~ aI-extends% I to the file attributes of the file

% ~ tI-extends% I to the date / time of the file

% ~ zI-extends% I to the size of the file

% ~ $PATH:I-find the directory listed in the path environment variable (TTT prompt: is the directory of the environment variable path) and expand% I to the first fully qualified name found. If the environment variable name is not defined, or if the file is not found, this key combination is extended to an empty string

In addition, you can combine modifiers to get multiple results:

% ~ dpI-extends% I to only one drive letter and path

% ~ nxI-extends% I only to a file name and extension

% ~ fsI-only extends% I to a full pathname with a short name

% ~ dp$PATH:i-find the directory listed in the path environment variable and expand% I to the first drive letter and path found.

% ~ ftzaI-extends% I to DIR with similar output lines

In the above example,% I and PATH can be replaced with other valid values. % ~ the syntax terminates with a valid FOR variable name. Selecting uppercase variable names like% I is easier to read and avoid confusion with case-insensitive key combinations.

(the above is the content of the system help)

We can see that each line has an uppercase letter "I", which is actually the variable we brought in in FOR, 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 the x _ fx,%~fy,%~fz _ y _ z to% ~ ~.

TTT special case: the following is a comprehensive example I made according to the above instructions, which can be copied directly to notepad and saved as bat format (any directory under disk c). After running, you can directly see the effect of the expansion.

@ echo off echo-shows "dir c:\ boot.ini / b / ah" for / f "delims=="% I in ('dir c:\ boot.ini / b / ah') do echo non-extended variable% I for / f "delims=="% I in (' dir c:\ boot.ini / b / ah') do echo extension variable to ~ fI% ~ fi-expand to a fully qualified pathname for / f "delims=="% I in ('dir c:\ boot.ini / b / ah') do echo extension variable to ~ dI% ~ di-expand variable to only one drive letter for / f "delims=="% I in (' dir c:\ boot.ini / b / ah') do echo extension variable to ~ pI% ~ pi-expand variable only to one path for / f "delims=="% I in ('dir c) :\ boot.ini / b / ah') do echo extension variable to ~ nI% ~ ni-- expand the variable to only one file name for / f "delims=="% I in ('dir c:\ boot.ini / b / ah') do echo extension variable to ~ xI% ~ xi-- expand the variable to only one file extension for / f "delims=="% I in (' dir c:\ boot.ini / b / ah') do Echo extension variable to ~ sI% ~ si-- the extension path contains only the short name for / f "delims=="% I in ('dir c:\ boot.ini / b / ah') do echo extension variable to ~ aI% ~ ai-- extends the variable to the file attribute for / f "delims=="% I in (' dir c:\ boot.ini / b / ah') do echo extension variable to ~ tI% ~ ti-- extends the variable to ~ tI% ~ ti Date / time extended to file for / f "delims=="% I in ('dir c:\ boot.ini / b / ah') do echo extension variable to ~ zI% ~ zi-expand variable to file size for / f "delims=="% I in (' dir c:\ boot.ini / b / ah') do echo extension variable to ~ $PATH:I% ~ $PATH:i-find directories listed in path environment variables And expand the variable to the first fully qualified name found, echo-- the following shows the combination modifier to get multiple results--: for / f "delims=="% I in ('dir c:\ boot.ini / b / ah') do echo extension variable to ~ dpI% ~ dpi-- expand the variable to only one drive letter and path for / f "delims=="% I in (' dir c) :\ boot.ini / b / ah') do echo extension variable to ~ nxI% ~ nxi-- expand the variable to only one file name and extension for / f "delims=="% I in ('dir c:\ boot.ini / b / ah') do echo extension variable to ~ fsI% ~ fsI-- expand the variable only to a full pathname for / f "delims=="% I in (' dir c:\ boot) with a short name .ini / b / ah') do echo extension variable to ~ dp$PATH:I% ~ dp$PATH:i-- find the directory listed in the path environment variable And expand 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% ~ ftzai-- expand the variable to DIR echo. Echo similar to the output line-- display "dir C:\ WINDOWS\ system32\ notepad.exe / b" for / f "delims=="% I in (' dir C: \ WINDOWS\ system32\ notepad.exe / b') do echo does not extend the variable% I for / f "delims=="% I in ('dir C:\ WINDOWS\ system32\ notepad.exe / b') do echo extension variable to ~ fI% ~ fi-- to a fully qualified pathname for / f "delims=="% I in (' dir C:\ WINDOWS\ system32\ notepad.exe / b') do echo extension variable to ~ dI% ~ di -- expand the variable to only one drive letter for / f "delims=="% I in ('dir C:\ WINDOWS\ system32\ notepad.exe / b') do echo extension variable to ~ pI% ~ pi-- expand the variable to a path for / f "delims=="% I in (' dir C:\ WINDOWS\ system32\ notepad.exe / b') do echo to ~ nI% ~ ni Filename for / f "delims=="% I in ('dir C:\ WINDOWS\ system32\ notepad.exe / b') do echo extension variable to ~ xI% ~ xi-- expand variable to only one file name extension for / f "delims=="% I in (' dir C:\ WINDOWS\ system32\ notepad.exe / b') do echo extension variable to ~ sI% ~ si-the expanded path contains only the short name for / f " Delims== "% I in ('dir C:\ WINDOWS\ system32\ notepad.exe / b') do echo extension variable to ~ aI% ~ ai-extend variable to file attribute for / f" delims== "% I in (' dir C:\ WINDOWS\ system32\ notepad.exe / b') do echo extension variable to ~ tI% ~ ti-extend variable to date / time for / f" delims== "% I in of the document ('dir C:\ WINDOWS\ system32\ notepad.exe / b') do echo extension variable to ~ zI% ~ zi-expand variable to file size for / f "delims=="% I in (' dir C:\ WINDOWS\ system32\ notepad.exe / b') do echo extension variable to ~ $PATH:I% ~ $PATH:i-find the directory listed in the path environment variable And expand the variable to the first fully qualified name found, echo-the following shows the combination modifier to get multiple results--: for / f "delims=="% I in ('dir C:\ WINDOWS\ system32\ notepad.exe / b') do echo extension variable to ~ dpI% ~ dpi-- expand the variable to only one drive letter and path for / f "delims=="% I in (' Dir C:\ WINDOWS\ system32\ notepad.exe / b') do echo extension variable to ~ nxI% ~ nxi-- expand the variable to only one file name and extension for / f "delims=="% I in ('dir C:\ WINDOWS\ system32\ notepad.exe / b') do echo extension variable to ~ fsI% ~ fsI-- expand the variable only to a full path 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 expand the variable to the first drive letter and path found, for / f "delims=="% I in ('dir C:\ WINDOWS\ system32\ notepad.exe / b') do echo extension variable to ~ ftzaI% ~ ftzai-- expand the variable to DIR Pause similar to the output line

TTT description:

1. In the above command,% ~ fsI cannot be displayed, which is estimated to be a system error, because% ~ fI is extended to a fully qualified path name, and% ~ sI contains only short text names, which is contradictory. I don't know if it's the fault of the system or it's testing us.

2, if the above command is saved on another disk, the correct drive and path cannot be displayed.

3. If you want%% ~ dp$PATH:i to display properly, make sure that this path does exist in the environment variable path: C:\ WINDOWS\ system32.

The following is explained in turn:

1. ~ I-remove any quotation marks (") and extend% I

The function of this variable is just as he explained, delete the quotation marks!

The rules for deleting quotation marks are as follows (added by brother BAT!):

1. If there are quotation marks at the beginning and end of the string, delete the quotation marks at the beginning and the end of the string

2. If there are no quotation marks at the end of the string, delete the quotation marks at the beginning of the string

3. If there are quotation marks in the middle of the string, or if there are only quotation marks at the end, they are not deleted.

Tornado added: every head does not delete, there is a head even tail deletion.

Let's take a look at this example, first create a temporary file temp.txt, which reads as follows

"1111

"2222"

3333 "

"4444" 44

"55" 55

You can also create a BAT file with the following code:

@ echo off echo ^ "1111 > temp.txt echo" 2222 "> temp.txt echo 3333 ^" > temp.txt echo "4444" 44 > > temp.txt echo ^ "55" 55 "55 > temp.txt rem creates a temporary file. Note that unpaired quotation marks should be escaped ^. Do not leave spaces FOR / F" delims= "% I IN (temp.txt) DO echo% ~ i pause del temp.txt before redirection.

After execution, we see the echo of CMD as follows:

The quotation marks before the 1111 # string have been deleted

The quotation marks at the beginning and end of the 2222 # string have been deleted.

3333 "# string is preceded by quotation marks, followed by quotation marks reserved

The quotation marks before the 4444 "44 # string are deleted, while the quotation marks in the middle are retained.

The quotation marks before the 55 "55" 55 # string are deleted, while the quotation marks in the middle are retained.

Please press any key to continue. . .

Comparing the result with the previous temp.txt, we will find that the quotation marks on lines 1, 2, and 5 have all disappeared, which is the purpose of deleting quotation marks ~ I!

2.% ~ fI-extends% I to a fully qualified pathname

Example:

Save the code anywhere, and I'll put it on the desktop here.

FOR / F "delims=="% I IN ('dir / b') DO @ echo% ~ fi

Pause

The content displayed after execution is as follows

C:\ Documents and Settings\ Administrator\ Desktop\ test.bat

C:\ Documents and Settings\ Administrator\ Desktop\ test.vbs

When I change% ~ 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 comparison, we can easily see that there is no path, which is the function of "extending% I to a fully qualified path name", that is, if the content of the% I variable is a file name, he will print out the absolute path where the file is located, instead of just printing a file name, you will know under the hands-on experiment!

3.% ~ dI-extend% I to only one drive letter

Look at the example:

The code is as follows, I will put it on the desktop for execution!

FOR / F "delims=="% I IN ('dir / b') DO @ echo% ~ di

Pause

After execution, my CMD shows the following

C:

C:

The test.bat,test.vbs,%%~di function of two files on my desktop is that if the content of the variable% I is a file or directory name, he will print out the disk symbol where the file or directory is located!

4.% ~ pI-extend% I to only one path

This usage is the same as above, it only prints the path, not the file name.

FOR / F "delims=="% I IN ('dir / b') DO @ echo% ~ pi

Pause

I will not play the results, you see the results, the following several are such a usage, the code is given, you see the results!

5.% ~ nI-extends% I to only one file name

Print only the file name

FOR / F "delims=="% I IN ('dir / b') DO @ echo% ~ ni

Pause

6.% ~ xI-extend% I to only one file extension

Print only the file extension

FOR / F "delims=="% I IN ('dir / b') DO @ echo% ~ xi

Pause

7.% ~ sI-the extended path contains only short names

Print an absolutely short file name

FOR / F "delims=="% I IN ('dir / b') DO @ echo% ~ si

Pause

8.% ~ aI-extends% I to the file attributes of the file

Properties of the print file

FOR / F "delims=="% I IN ('dir / b') DO @ echo% ~ ai

Pause

9.% ~ tI-extends% I to the date / time of the file

Date on which the print file was created

FOR / F "delims=="% I IN ('dir / b') DO @ echo% ~ ti

Pause

10.% ~ zI-extends% I to the size of the file

The size of the print file

FOR / F "delims=="% I IN ('dir / b') DO @ echo% ~ zi

Pause

Add: "delims==" in the above example can be changed to "delims=", that is, no delimiter

% ~ $PATH:I-find the directory listed in the path environment variable and extend% I to the first fully qualified name found. If the environment variable name is not defined, or if the file is not found, this key combination is extended to an empty string

This is the last one, which is different from the ones above. I'll talk about it 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

Add: the above code shows the result as C:\ WINDOWS\ system32\ notepad.exe

He means to search the notepad.exe file in the path specified in the PATH variable, and if there is a notepad.exe, it will print out his absolute path, and if not, print an error!

(TTT description, save to the desktop, run the display result is: the system cannot find the file "notepad.exe". Check that this path does exist in the environment variable path. I don't know why! Later, it was discovered that it was the reason for the Chinese quotation marks.

The above command should read:

FOR / F "delims="% I IN ("notepad.exe") DO echo% ~ $PATH:i

)

The above is all the contents of the article "sample Analysis of dos batch for Loop commands". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report