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

DOS batch commands For Loop commands how to use the

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

Share

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

This article mainly introduces the DOS batch command For loop command how to use, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.

For command is a kind of command that runs on the command line or batch to execute the same or more commands on a series of objects in turn. Combined with some programs in Windows management, its processing function is powerful and its application is flexible and convenient. However, the complexity of its help information is often daunting to beginners. Here, according to my understanding, it is inevitable to decompose and simplify its usage, negligence and mistakes.

Basic format

(what is written here is the format used on the command line. If you are in a batch, you need to add% to form%%):

For / Parameter% variable in (set) do command

(note: except for Chinese, the rest are written according to its format, both uppercase and lowercase.)

Parameters: FOR is divided into four parameters D L R F, and some parameters can be added with additional options, which will be described below.

Variable: (remember that if you use the for command in a batch, the% in front of the variable needs to be changed to%%) the variable name is composed of a single letter and is case-sensitive (the original help said so, it is also possible to use a single number as the variable name in practice), such as% B and% b represent different variables.

The FOR command assigns the value read in in (set) to this variable in each loop so that it can be referenced in subsequent commands.

Set: a collection formed by a series of files, strings, or content generated by a command (wildcard characters are available, of course. (environment variables can also be referenced), the FOR command reads the contents of the set in a certain order and rules, assigns values to variables, and executes the command after do to cycle the next round until the contents of the collection are read, and parentheses are required in format (there is a space between in and parentheses after the parenthesis).

Commands: it can be any qualified DOS command or an external program that can be called by DOS, and multiple commands can be enclosed in parentheses and executed in one loop.

Note: because some directories or file names may have spaces, many sets and commands often need to be enclosed in English quotation marks (but sometimes the contents in quotation marks may be thought of as a string). Some of the examples below ignore the file name or directory name with spaces for the sake of simplicity.

Now give examples to explain its usage according to the classification of parameters:

1. Parameter / d

For / d% variable in (set) do command

The / d parameter is a for command that specifies that only directories, not files, are executed.

Example 1:

Enter on the command line (not in batch, not explained later)

For / d% an in (c:\ *. *) do echo% a

The run will display all the directories under the root directory of the C disk in stages instead of the file name.

It looks a little messy, but it will be clear if you turn off the command prompt:

For / d% an in (c:\ *. *) do @ echo% a

Second, parameter / R

The / R parameter can be followed by a drive letter and a path

For / r here you can take 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 scope in the DOS command tree), if it is only one English period. Refers to the directory tree under the current path, or the current directory if the path is omitted, while the subsequent in (set) is equivalent to the set of files that match each previous directory

There are two cases here according to whether there are wildcards in in (set) or not.

1) there are no wildcards in in (set)

Specify a single file or enumerated specific file (multiple file names are separated by delimiters, such as spaces, commas, etc.)

Example 2

@ echo offor / r. % I in (abc.txt) do echo. > iecho on

Note: there is only one path after for / r. However, in each subsequent cycle, echo. >% I is equivalent to creating a text file with only one blank line. The overall effect is to include subdirectories in the current directory, with an abc.txt in each directory.

Example 3 (put in batch)

@ echo offrem shows a list of all files named file1 and file2 in d: disk for / r d:\% h in (file1,file2) do if exist% h echo% hpause

2) in (set) contains wildcard characters * or?

The do command in this will deal with each item in the directory series specified above that contains files in in, regardless of those directories that do not contain matching files.

Example 4:

@ echo offrem deletes all * .chk files in disk C for / r c:\% h in (* .chk) do del / Q% hpause

Note: del / Q means to delete in quiet mode (no confirmation is required)

3. Parameter / L

For / L%% variable in (start value, each increment, end comparison value) do command

(upper L can also be lowercase, mainly in order not to be visually confused with the number 1.)

(the starting value, each increment, the comparison value at the end) is equivalent to a sequence of isometric numbers, starting from the number of the "starting value", the amount of each increase (which can also be set to a negative number) to "each increment", and compared with the "comparison value at the end", if you exceed it, exit the for loop (and do not execute the do command later in this round)

For example, (1) the sequence will be generated (1 23); (1) the sequence will be generated (13 57 9); (5) the sequence will be generated (5 4 3 21); (1 3) the sequence will be generated (1 7 10 13 16).

Example 5

@ echo off:: create aa1~ aa5 five folders on disk D for / L% I in do md d:\ aa% ipause

Note: at the beginning of the line, a single colon: followed by a name, is the label line, corresponding to the location pointed to after go in the batch, while the double colon:: is generally used for comments, comments in the batch can be expressed with rem plus spaces, the two are slightly different, rem comments will be displayed on the screen when the command echo is not closed, and:: will not be displayed under any circumstances.

IV. Parameter / f

This parameter / f will open the file in the set, so that the for command can handle editorial operations such as reading and adding, deleting and replacing text files, which is powerful and relatively complex.

File name-set

For / f "options"% variable in (string-set) do command

'Command'- set

/ f can be followed by several options, of course, it is a qualified format without options, while parameters must be enclosed in quotation marks as a whole. The subsequent sets are mainly formed by three forms. Finally, in each round of the for loop, it is formed to read a line of strings to assign values to the specified% variables and additional variables derived from the options, then execute the commands following do.

The following examples are used to illustrate and gradually understand the usage of each section.

Example 6

Suppose d:\ abc.txt contains the following:

Name, sex, age, etc.

Zhang San male 36 A Murray 1

Li Si male 29 B Mei 2

Zhao Liunu 31 Amura 2

Execute the following command:

For / f% c in (d:\ abc.txt) do @ echo% c

Then the screen displays:

Name

Zhang San

Li Si

Zhao Liu

Explanation: this is the case when for / r defaults to the parameter option before "% variable". Each round of the loop is separated by spaces by default, and the string is segmented line by line in the open file, and because no additional variable is added (that is, only one variable% c), only the characters of the first paragraph are assigned to% c, then execute the command after do, and then proceed to the next round of the loop, and ignore blank lines by default.

Change it:

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

It is displayed as:

Zhang San Amur1

Li Si BMI 2

Zhao Liu Amur2

Solution:

Skip=1 indicates that the number of lines that the text begins to ignore is 1-several lines are ignored

Delims= in a line, what single symbol (there can be a combination of multiple characters, there can be no spaces between them, is understood as multiple single characters, such as spaces must be placed at the end) to separate the string as a unit for reading assignments (to form a paragraph). In this example, the space after the equal sign is separated by spaces only. -- what knife is used to cut it?

The number after the equal sign tokens=1,4 indicates that the separated string segments are assigned to% variables and sequentially appended variables, respectively. In this example, the first paragraph is assigned to% c, and the fourth paragraph is assigned to% d, and It can be written as tokens=1,2,5-7 or tokens=1,2,3* or tokens=1,2,5,7 to take the 1st, 2nd, 5th, 6th and 7th (5 variables assigned to% c,% d,% e,% f,% g in turn), 1 to 2 and all the paragraphs after 3 (to be assigned to 3 variables), 1 to 2 to 5 to 7 (to be assigned to 4 variables), respectively, the numeral numbers after tokens= can be out of order, but the order of writing corresponds to the order assigned to the variables, which is an assignment. Whether or not to use it later in the do command is another matter. In other words, which paragraphs need to be taken at most?

The variable in in (variable) represents the starting variable name and expands the additional variable name according to the total number defined in tokens. If the total number is 3,% c appends% d and% e, and if% C appends% D% E... In this example, only two tokens=1,4 are needed, starting with% c in in () parentheses, the first paragraph of each line is assigned to% c, and paragraph 4 is assigned to the variable% d

Take the second line (the first line is skipped by skip=1) as an example, in "Zhang Sannan 36 A murl 1" (which happens to be separated by a space), it is cut into five paragraphs by the space knife, as long as the 1st and 4th, that is, Zhang San assigns% c, AME 1 is assigned to% d, execute @ echo% c% d and then the next round … And the blank line is still omitted.

Change it a little bit:

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

Is displayed as:

A Zhang San

B Li Si

A Zhao Liu

Example 7

Suppose d:\ aa.txt contains the following:

Volume in drive D is MYDA

Volume Serial Number is C35D-8998

Directory of D:tmp

09/25/2001 10:40 AM 11235 yg0925.txt

11/12/2001 04:29 pM 795 buple.txt

04/11/2002 04:18 AM 2043 vitn.txt

3File (s) 12673 bytes

0 Dir (s) 5020200655 bytes free

On the command line, enter:

For / f "skip=5 tokens=5"% an in (d:\ aa.txt) do @ echo% a

The following is displayed:

Yg0925.txt

Buple.txt

Vitn.txt

Free

It is intended to display the files listed in the file (of course, it can also be replaced with other command operations on the file)

Ignore the first five lines through skip=5, by default separated by spaces after tokens=5 takes each line of the fifth paragraph of characters to smoothly assign the file name to the variable% a, the last line is not a file name (of course, you can use other ways to deal with this extra only for/f does not provide to ignore the last few lines of the format), and the penultimate line does not have the fifth paragraph.

Obviously, the content in the aa.txt in the example is the content after the execution of the dir command. It can use similar commands:

Dir > d:\ aa.txt to create

Beside the question, if you add the appropriate parameter / b to dir, you can avoid the superfluous parts, and you can also add / ad to show only directories, and / aMud to display only files, etc.

So, we can write the command directly and put it in the ('command'-set) after in.

For / f "skip=5 tokens=5" an in ('dir') do @ echo a

The effect is the same.

Note: the command set needs to be enclosed in single quotation marks to indicate that it is not a file set, and if enclosed in double quotation marks, it is a string set. This example is to illustrate the use of the for command, which is really useful and willing to use the previous "digression" method. If you don't show anything after executing this example, you need to use the command in the set first to see the format it displays, maybe you need to change tokens=5 to tokens=4, or you should add the parameter / a house d to dir to avoid showing the directory.

If the set consists of multiple files, then one file is processed and then another file is processed, and the number of loops per file line (the number of do commands) will be different.

If the system in the set is generated by the command, you must first be familiar with the character system of what effect the command will produce after the command is executed before you can correctly arrange the following do commands

Finishing point: no matter which form the set is after in, for/f is finally decomposed into strings, according to whether to "ignore a few lines" (skip=), "what knife to split" (delims=), "up to which paragraph" (tokens=) will be the string formed in the set, line by line segments assigned to% or% of the variables and may be extended after the variable, in order to implement the command after do, each line is a cycle. All the parameters are not fully described here, please use for/? on the command line Check. (the following italics are copied from the help)

For example:

For file names with spaces, you need to enclose the file name in double quotes. To use double quotes in this way, you also need to use the usebackq option; otherwise, double quotes are understood to be used to define a string to be parsed. In other words, the file name is still indicated in double quotation marks in in () with the parameter usebackq (in quotation marks after for / f).

There is also an option eol=: skip= means to ignore the first few lines, but in fact, all semicolons are ignored by default. If you want not to ignore the line starting with the semicolon, or if you want to ignore the line starting with a character you specify, you can use the characters defined by eol= in the quotation mark parameter after for / f, but it is not allowed to define multiple characters, only one is allowed.

Another trick: you can use the% ~ operator to separate the file name into separate parts such as file name, extension, drive letter, etc. See for/? (where the variable in the example is% I):

In addition, 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 and extend% I

To the first fully qualified name found. If the environment variable name

If the file is not defined or the file is not found, this key combination will be extended to an empty string

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 extend% I

To the first drive letter and path found.

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

Brief note: any operator that starts with% ~ is a separation operation of file name or environment variable. And if you want to use each item freely, you need to practice hard.

Exercise: (I'm a little lazy and don't do it myself.)

Traverse C and D disks to find known file names (receive keyboard input), and record their storage location and time to D:\ mynote.txt record format such as:

Xx xx month xx day to find the xx files on disk C and D are as follows:

Time and position

. .

. .

. .

.

.

.

Hint: possible DOS commands, variables, parameters: echo, set, set/p,% date%,% ~ >, > >

Summary and hints:

The actual use of the for command is basically over, but only this can not write a powerful batch processing, it is only a DOS command, need to be proficient in some other DOS commands and commands provided by the Windows system, combined use, in order to give full play to its powerful and practical functions, making some complex things, dealing with unexpected simplicity and convenience.

Attachment: a command or environment setting commonly needed in batch for commands:

The for command actually makes a loop. If you change the value of an environment variable in each round of the command, and in the default state, a for command takes the value only once with the% environment variable%, then the value before the change in the next cycle (including the execution period of multiple commands followed by parentheses in do) will not achieve the desired purpose. For this reason, the following command is introduced:

Setlocal enabledelayedexpansion

Start the localization of environment changes in the batch file and start the deferred environment variable extension. When the execution SETLOCAL reaches the end of the batch file, an implied endlocal is executed for each outstanding setlocal command of the batch file.

When taking the value of a variable, use! Variable name! You can take values dynamically, and deferred environment variable expansion allows you to extend the environment variable at execution time with a different character (exclamation point). This usage actually belongs to all compound commands that need to be noted in batch processing. If you do not want to retain the changed environment at the end of the batch, it is always recommended to add setlocal.

If the combination of some other complex system-related, network commands (such as wmic, net) come in, that is to show the heroic nature of FOR, such as traversing the local disk can be used with commands: wmic logicaldisk where "drivetype=3" get name obviously in all disks to find a file and do the corresponding operation is very easy, good use of for commands also need other commands and computer foundation with. Oh, my level is limited, what I write is only at a low level. I hope it will be helpful to the novice DOS commanders who are lucky to come here to see it.

Thank you for reading this article carefully. I hope the article "how to use DOS batch commands For Loop commands" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

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