> DOS 中文参考手册 > for

FOR

(for)


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

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

  %variable       指定一个单一字母可替换的参数。

  (set)             指定一个或一组文件。可以使用通配符。

  command       指定对每个文件执行的命令。

  command-parameters   为特定命令指定参数或命令行开关。

在批处理文件中使用 FOR 命令时,指定变量请使用 %%variable而不要用 %variable。变量名称是区分大小写的,所以 %i 不同于 %I.

如果命令扩展名被启用,下列额外的 FOR 命令格式会受到支持:

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

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

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

    检查以 [drive:]path 为根的目录树,指向每个目录中的FOR 语句。如果在 /R 后没有指定目录,则使用当前目录。如果集仅为一个单点(.)字符,则枚举该目录树。

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]

    filenameset 为一个或多个文件名。继续到 filenameset 中的下一个文件之前,每份文件都已被打开、读取并经过处理。

    处理包括读取文件,将其分成一行行的文字,然后将每行解析成零或更多的符号。然后用已找到的符号字符串变量值调用 For 循环。以默认方式,/F 通过每个文件的每一行中分开的第一个空白符号。跳过空白行。您可通过指定可选 "options" 参数替代默认解析操作。这个带引号的字符串包括一个或多个指定不同解析选项的关键字。这些关键字为:

        eol=c           - 指一个行注释字符的结尾(就一个)

        skip=n          - 指在文件开始时忽略的行数。

        delims=xxx      - 指分隔符集。这个替换了空格和跳格键的默认分隔符集。

        tokens=x,y,m-n  - 指每行的哪一个符号被传递到每个迭代的 for 本身。这会导致额外变量名称的分配。m-n格式为一个范围。通过 nth 符号指定 mth。如果符号字符串中的最后一个字符星号,那么额外的变量将在最后一个符号解析之后分配并接受行的保留文本。

        usebackq        - 指定新语法已在下类情况中使用:

                          在作为命令执行一个后引号的字符串并且一个单引号字符为文字字符串命令并允许在 filenameset中使用双引号扩起文件名称。

    某些范例可能有助:

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 是通过okens= 选项专门得到说明的。您可以通过 tokens= 一行指定最多 26 个符号,只要不试图说明一个高于字母 'z' 或'Z' 的变量。请记住,FOR 变量是单一字母、分大小写和全局的;而且,同时不能有 52 个以上都在使用中。

    您还可以在相邻字符串上使用 FOR /F 分析逻辑;方法是,用单引号将括号之间的 filenameset 括起来。这样,该字符串会被当作一个文件中的一个单一输入行。

    最后,您可以用 FOR /F 命令来分析命令的输出。方法是,将括号之间的 filenameset 变成一个反括字符串。该字符串会被当作命令行,传递到一个子 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   - 查找列在路径环境变量的目录,并将 %I 扩充到找到的第一个完全合格的名称。如果环境变量名未被定义,或者没有找到文件,此组合键会扩充到空字符串

可以组合修饰符来得到多重结果:

     %~dpI       - 仅将 %I 扩充到一个驱动器号和路径

     %~nxI       - 仅将 %I 扩充到一个文件名和扩展名

     %~fsI       - 仅将 %I 扩充到一个带有短名的完整路径名

     %~dp$PATH:i - 查找列在路径环境变量的目录,并将 %I 扩充到找到的第一个驱动器号和路径。

     %~ftzaI     - 将 %I 扩充到类似输出线路的 DIR

在以上例子中,%I 和 PATH 可用其他有效数值代替。%~ 语法用一个有效的 FOR 变量名终止。选取类似 %I 的大写变量名比较易读,而且避免与不分大小写的组合键混淆。 

★★★★★实例★★★★★:

假设你想用TYPE命令来显示当前目录下扩展名.DOC或.TXT的所有文件的内容。为了做到这一点要使用可替代变量%F,并在命令提示符下输下面的命令。

for %f in (*.doc *.txt) do type %f

在此例中,当前目录下扩展名为.DOC或.TXT的每一个文件将代替%F变量,直到显示出每一个文件的内容为止。若把每一个%F都替换成%%F,则此命令可用于一批处理文件。否则,MS-DOS将忽略此变量而显示错误信息。

MS-DOS支持你想用于特定命令的开关、管道及重定向符。例如,为了把前一例的输出送到PRN(默认打印机口),应输入下面的命令:

for %f in (*.doc *.txt) do type %f > prn:


Runs a specified command for each file in a set of files.

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

  %variable  Specifies a single letter 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.  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 just a single period (.) character then it will just 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]

    filenameset is one or more file names.  Each file is opened, read and processed before going on to the next file in filenameset.

    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.  This is a quoted string which contains one or more keywords to specify different parsing options.  The keywords are:

        eol=c           - specifies an end of line comment character (just one)

        skip=n          - specifies the number of lines to skip at the beginning of the file.

        delims=xxx      - specifies a delimiter set.  This replaces the default delimiter set of space and tab.

        tokens=x,y,m-n  - specifies which tokens from each line are to be passed to the for body for each iteration.

                          This will cause additional variable names to be allocated.  The m-n form is a range, specifying the mth through the nth tokens.  If specifying the mth through the nth tokens.  If the last character in the tokens= string is an asterisk, then an additional variable is allocated and receives the remaining text on the line after the last token parsed.

        usebackq        - specifies that the 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 and allows the use of double quotes to quote file names in filenameset.

    Some examples might help:

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

    would parse each line in myfile.txt, ignoring lines that begin with a semicolon, passing the 2nd and 3rd token from each line to the for body, with tokens delimited by commas and/or 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 filenames with double quotes.  In order to use double quotes in this manner, you also need to use the usebackq option, otherwise the double quotes will be need to use the usebackq option, otherwise the double quotes will be 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 variables are single-letter, 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 immediate string, by making the filenameset between the parenthesis a quoted string, using single quote characters.  It will be treated as a single line of input from a file and parsed.

    Finally, you can use the FOR /F command to parse the output of a command.  You do this by making the filenameset between the parenthesis a back quoted string.  It will be treated as a command line, which is passed to a child CMD.EXE and the output is captured into memory and parsed as if it was 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.

In addition, substitution of FOR variable references has been enhanced.

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 file

    %~tI        - expands %I to date/time of file

    %~zI        - expands %I to size of 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 above examples %I and PATH can be replaced by other valid values.  The %~ syntax is terminated by a valid FOR variable name.

Picking upper case variable names like %I makes it more readable and avoids confusion with the modifiers, which are not case sensitive.


上一篇:
下一篇: