for (对一组文件中的每一个文件执行某个特定命令)

小猪老师 发表于 2020-06-22 17:09
浏览次数:
在手机上阅读

批处理文件使用FOR变量在满足或声明参数时运行特定命令。

查看英文版

目录

1 for 运行系统环境

2 for syntax

3 for 示例

for 运行系统环境

Windows 95

Windows 98

Windows xp

Windows vista

Windows 2000

Windows 7

Windows 8

Windows 10

Windows NT

Windows ME

All Versions of MS-DOS

for syntax

Windows 2000, XP和更高版本的语法

FOR %variable IN (set) DO command [command-parameters]
%variable 一个任意的参数。
(fileset) 指定一组一个或多个文件。可以使用通配符。
command 指定要为每个文件执行的命令。
command-parameters 指定命令的参数或开关。

若要在批处理程序中使用FOR命令,请指定%%变量而不是%变量。
变量名是区分大小写的,所以%i不同于%i。

如果命令扩展被启用,下面的FOR命令的其他形式被支持:

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

如果set包含通配符,则指定与目录名而不是文件名匹配。

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

遍历以[drive:]路径为根的目录树,在树的每个目录中执行FOR语句。如果在/R之后没有指定目录规范,则假设为当前目录。如果set只有一个句点(.)字符,那么它将枚举目录树。

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

这个集合是一个数字序列,从开始到结束,按步进的数量。所以(1,1,5)会生成序列1 2 3 4 5,而(5,-1,1)会生成序列(5 4 3 2 1)

FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ("string") DO command [command-parameters]
FOR /F ["options"] %variable IN ('command') DO command [command-parameters]

或者,如果存在usebackq选项:

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]

参数fileset是作为输入源的一个或多个文件名。filenameset中的每个文件都被打开、读取和处理,然后再继续下一个文件。处理包括读取文件,将其分解为单独的文本行,然后将每行解析为零个或多个标记。然后调用for循环的主体,并将变量值设置为找到的标记字符串。默认情况下,/F从每个文件的每一行传递第一个空白分隔标记。空行被跳过。您可以通过指定可选的“options”参数来覆盖默认的解析行为。带引号的字符串包含一个或多个关键字,用于指定不同的解析选项。
关键字:

eol=c 指定行尾注释单。
skip=n 指定文件开头要跳过的行数。
delims=xxx 指定分隔符集,用于替换空格和制表符的默认分隔符集。
tokens=x,y,m-n

指定在每次迭代中从每行中传递给for主体的标记,这将导致分配额外的变量名。

m-n形式是一个范围,指定第m个标记到第n个标记。

如果令牌=字符串中的最后一个字符是星号,则分配一个额外的变量,

并接收最后解析的令牌之后的剩余行文本。

usebackq

指定生效的新语义,其中后引的字符串作为命令执行,单引的字符串是文本字符串命令。

选项还允许使用双引号引用文件集中的文件名。

下面的例子可能会有所帮助:

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

解析myfile.txt,忽略以分号开头的行,将每行中的第二和第三个标记传递给for主体,标记由逗号和空格分隔。注意for主体语句引用%i来获得第二个令牌,引用%j来获得第三个令牌,引用%k来获得第三个令牌之后的所有剩余令牌。对于包含空格的文件名,需要使用双引号引用文件名。要以这种方式使用双引号,需要使用usebackq选项。否则,双引号将被解释为定义要解析的文字字符串。

%i是在for语句中显式声明的,而%j和%k是通过tokens    =选项隐式声明的。
您可以通过tokens=行指定多达26个令牌,只要它不会导致声明大于字母'z'或'Z'的变量。
记住,FOR变量名是区分大小写的、全局的,并且一次最多不能有超过52个活动变量。

还可以对任意字符串使用FOR /F解析逻辑。为此,将fileset指定为用圆括号括起来的单引号字符串。它将被解析为来自文件的单行输入。

最后,可以使用FOR /F命令来解析命令的输出。通过使括号之间的文件集成反引号字符串,它被视为命令行,传递给子CMD.EXE,其输出被捕获到内存中并作为文件进行解析。
下面这个例子:

FOR /F "usebackq delims==" %i IN (`set`) DO @echo %i

将枚举当前环境中的环境变量名。

FOR变量引用的替换增强了,现在可以使用以下可选语法:

%~I 扩展%I,删除周围的引号(")。
%~fI 将%I展开为完全限定的路径名。
%~dI 仅将%I扩展为驱动器号。
%~pI 将%I扩展为仅路径。
%~nI 将%I扩展为文件名。
%~xI 仅将%I扩展为文件扩展名。
%~sI 展开路径只包含短名称。
%~aI 将%I展开为文件的文件属性。
%~tI 将%I扩展到文件的日期/时间。
%~zI 将%I扩展为文件的大小。
%~$PATH:I

搜索PATH环境变量中列出的目录,并将%I展开为找到的第一个目录的完全限定名。

如果没有定义环境变量名,或者搜索没有找到该文件,则此修饰符将展开为空字符串。

可以组合修饰符得到复合结果:

%~dpI 将%I扩展为驱动器符和路径。
%~nxI 将%I扩展为文件名和扩展名。
%~fsI 将%I扩展为仅具有短名称的完整路径名。
%~dp$PATH:i 搜索PATH环境变量中列出的目录%I,并展开到第一个找到的驱动器号和路径。
%~ftzaI 将%I展开到类似于DIR的输出行。

在上面的示例中,%I和PATH可以替换为其他有效值。语法以一个有效的变量名结束。选择像%I这样的大写变量名使其更具可读性,并避免与不区分大小写的修饰符混淆。

Windows 95, 98, ME 语法

FOR %variable IN (set) DO command [command-parameters]
%variable 指定可替换参数。
(set) 指定一组一个或多个文件。可以使用通配符。
command 指定要为每个文件执行的命令。
command-parameters 指定命令的参数或开关。

若要在批处理程序中使用FOR命令,请指定%%变量而不是%变量。

Windows 2000, XP, and later syntax

FOR %variable IN (set) DO command [command-parameters]
%variable An arbitrary parameter.
(fileset) Specifies a set of one or more files. Wildcards may be used.
command Specifies the command to carry out for each file.
command-parameters Specifies parameters or switches for the specified command.

To use the FOR command in a batch program, specify %%variable instead of %variable. Variable names are case-sensitive, so %i is different from %I.

If Command Extensions are enabled, the following additional forms of the FOR command are supported:

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

If set contains wildcards, then specifies to match against directory names instead of file names.

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

Walks the directory tree rooted at [drive:]path, executing the FOR statement in each directory of the tree. If no directory specification is specified after /R, then the current directory is assumed. If set is only a single period (.) character, then it will enumerate the directory tree.

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

The set is a sequence of numbers from start to end, by step amount. So (1,1,5) would generate the sequence 1 2 3 4 5 and (5,-1,1) would generate the sequence (5 4 3 2 1).

FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ("string") DO command [command-parameters]
FOR /F ["options"] %variable IN ('command') DO command [command-parameters]

or, if usebackq option present:

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 parameter fileset is one or more file names that are the source of input. Each file in filenameset is opened, read, and processed before going on to the next one. Processing consists of reading in the file, breaking it up into individual lines of text, and then parsing each line into zero or more tokens. The body of the for loop is then called with the variable value(s) set to the found token string(s). By default, /F passes the first blank separated token from each line of each file. Blank lines are skipped. You can override the default parsing behavior by specifying the optional "options" parameter. A quoted string contains one or more keywords to specify different parsing options. The keywords are:

eol=c Specifies an end of line comment single.
skip=n Specifies the number of lines to skip at the beginning of the file.
delims=xxx Specifies a delimiter set, which replaces the default delimiter set of space and tab.
tokens=x,y,m-n Specifies what tokens from each line are to be passed to the for body for each iteration, which causes additional variable names to be allocated. The m-n form is a range, specifying the mth through the nth tokens. If the last character in the tokens= string is an asterisk, an additional variable is allocated and receives the remaining line text after the last token parsed.
usebackq Specifies new semantics are in force, where a back quoted string is executed as a command, and a single quoted string is a literal string command. Option also allows the use of double quotes to quote file names in fileset.

Some examples might help:

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

parses myfile.txt, ignoring lines beginning with a semicolon, passing the 2nd and 3rd token from each line to the for body, with tokens delimited by commas and spaces. Notice the for body statements reference %i to get the 2nd token, %j to get the 3rd token, and %k to get all remaining tokens after the 3rd. For file names that contain spaces, you need to quote the file names with double quotes. To use double quotes in this manner, you need to use the usebackq option. Otherwise, the double quotes are interpreted as defining a literal string to parse.

%i is explicitly declared in the for statement, and the %j and %k are implicitly declared via the tokens= option. You can specify up to 26 tokens via the tokens= line, provided it does not cause an attempt to declare a variable higher than the letter 'z' or 'Z'. Remember, FOR variable names are case-sensitive, global, and you can't have more than 52 total active at any one time.

You can also use the FOR /F parsing logic on an arbitrary string. To do so, specify fileset as a single-quoted string enclosed in parentheses. It will be parsed as a single line of input from a file.

Finally, you can use the FOR /F command to parse the output of a command. You do this by making the fileset between the parenthesis a back quoted string. It's treated as a command line, which passes to a child CMD.EXE and its output is captured into memory and parsed as a file. So the following example:

FOR /F "usebackq delims==" %i IN (`set`) DO @echo %i

would enumerate the environment variable names in the current environment.

The substitution of the FOR variable references were enhanced, and you can now use the following optional syntax:

%~I Expands %I removing any surrounding quotes (").
%~fI Expands %I to a fully qualified path name.
%~dI Expands %I to a drive letter only.
%~pI Expands %I to a path only.
%~nI Expands %I to a file name only.
%~xI Expands %I to a file extension only.
%~sI Expanded path contains short names only.
%~aI Expands %I to file attributes of the file.
%~tI Expands %I to date/time of the file.
%~zI Expands %I to size of the file.
%~$PATH:I Searches the directories listed in the PATH environment variable and expands %I to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string.

The modifiers can be combined to get compound results:

%~dpI Expands %I to a drive letter and path only.
%~nxI Expands %I to a file name and extension only.
%~fsI Expands %I to a full path name with short names only.
%~dp$PATH:i Searches the directories listed in the PATH environment variable for %I and expands to the drive letter and path of the first one found.
%~ftzaI Expands %I to a DIR like output line.

In the examples above, %I and PATH can be replaced by other valid values. The %~ syntax is terminated by a valid FOR variable name. Picking uppercase variable names like %I makes it more readable and avoids confusion with the modifiers, which are not case-sensitive.

Windows 95, 98, ME syntax

FOR %variable IN (set) DO command [command-parameters]
%variable Specifies a replaceable parameter.
(set) Specifies a set of one or more files. Wildcards may be used.
command Specifies the command to carry out for each file.
command-parameters Specifies parameters or switches for the specified command.

To use the FOR command in a batch program, specify %% variable instead of % variable.

查看英文版

查看中文版

for 示例

for /F %%A in ("pics.txt") do If %%~zA equ 0 del pics.txt

在上面的示例中,如果在当前目录中找到了pics.txt文件,并且文件大小为0,则该文件将被删除。

for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "hope.txt" %%e-%%f-%%g.txt

上面的示例从%date%中获取日期,并使用其数据将hope.txt文件重命名为当前日期。

for /f %F in ('dir /b /a-d ^| findstr /vile ".tiff .jpg"') do del "%F"

上面的for命令将删除当前目录中不以.tiff或.jpg结尾的所有内容。

for /F %%A in ("pics.txt") do If %%~zA equ 0 del pics.txt

In the above example, if the file pics.txt was found in the current directory and was equal to 0 in file size, that file would be deleted.

for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "hope.txt" %%e-%%f-%%g.txt

The example above takes the date from %date% and uses its data to rename the hope.txt file to the current date.

for /f %F in ('dir /b /a-d ^| findstr /vile ".tiff .jpg"') do del "%F"

The for command above would delete everything in the current directory that did not end with a .tiff or .jpg.

查看英文版

查看中文版

其他命令行

fasthelp | fc | fciv | fdisk | find | findstr | fixboot | fixmbr | forfiles | format | ftp | ftype |

如此好文,分享给朋友
发表评论
验证码:
评论列表
共0条