for命令是一种对一系列对象依次循环执行同一个或多个命令的在命令行或批处理中运行的命令,结合一些Windows管理中的程序后,其处理功能强大、应用灵活方便程度令人刮目相看。但是,其帮助信息也因此复杂往往令初学者望而生畏,这里根据本人的学习理解,把其用法分解简化,疏忽和错误也许在所难免。
基本格式
(这里写的是在命令行里用的格式,如果是在批处理中,需要把其中%再多加个%形成%%):
for /参数 %变量 in (集) do 命令
(注:上面除中文的以外,其余的是按它的格式要求书写的,大小写都行)
参数:FOR分四种参数 D L R F,并且有的参数还可附加另外的选项下面会分别介绍
变量:(记住如果是在批处理中使用for命令时,变量前的%需改为%%)这个变量名是由单个字母组成且区分大小写(原帮助是这么说的,实际运用中用单个数字作为变量名试过证明也可行),如%B和%b代表的是不同的变量。
FOR命令会在每次循环中,把in (集)中读取到的值赋于这个变量,以便其后的命令中引用。
集:由系列文件、字符串或由命令产生的内容形成的集合(当然可用通配符 * ?,还可引用环境变量),FOR命令是按一定顺序和规律分次读取集中内容,赋值给变量,并执行do后的命令,进行循环下一轮,直至集中内容读取完毕,而括号是格式必须的(in到后面括号之间要有空格)。
命令:可以是任何合格的DOS命令或外部可被DOS调用的程序,且可采用括号把多条命令括起来,在一次循环中执行。
附注:由于一些目录或文件名可能会有空格,所以很多时候集里和命令里往往需要用英文引号括起来(但有时引号里的内容可能会被认为是字符串)表示是一整体,下面开始的有些例中为简捷起见,忽略文件名或目录名带空格这种情况。
现在按参数分类举例解释其用法:
一、参数 /d
for /d %%变量 in (集) do 命令
/d 参数是指定仅对目录而不是文件执行的for命令。
例1:
在命令行输入(不是在批处理,之后不再解释)
for /d %a in (c:\*.*) do echo %a
运行会把C盘根目录下的全部目录分次显示出来,而不显示文件名
看起来有点乱,如果把命令提示回显关闭就清晰了:
for /d %a in (c:\*.*) do @echo %a
二、参数 /R
/R参数之后还可带盘符及路径
for /r 此处可以带有路径 %变量 in (集) do 命令
在/r 之后的那个路径,指包含它之下的整个目录树(相当于DOS命令tree里的范围)中的所有目录,如果仅为一个英文句点 . ,是指当前路径下的目录树,如果省略了路径则特指当前目录,而之后的in (集)则相当于与前面每个目录相配的文件集
这里按in(集)中有无通配符分两种情况
1) in(集)中没有通配符
指定的是单个文件或列举的具体文件(多个文件名之间用分隔符分隔,如空格、逗号等)
例2
@echo of
for /r . %i in (abc.txt) do echo. > %i
echo on
注:这里for /r 后的路径仅有一个 . 而后面每个循环中echo. > %i相当于创建一个仅有一空行的文本文件,整体效果是在当前目录下包括子录,每个目录中建一个abc.txt。
例3 (放入批处理中)
@echo off
rem 显示d:盘中所有文件名为file1和file2的列表
for /r d:\ %%h in (file1,file2) do if exist %%h echo %%h
pause
2) in(集)中含有通配符*或?
这种里面的do命令将处理前面 /r指定的目录系列里每个含有in(集)中文件的项,而不去理会不含有相配文件的那些目录
例4:
@echo off
rem 删除C盘中所有*.chk的文件
for /r c:\ %%h in (*.chk) do del /q %%h
pause
注:del /q 表示用安静模式删除(不需确认)
三、参数 /L
for /L %%变量 in (起始值,每次增值,结束时的比较值) do 命令
(上面L也可用小写,主要为了视觉上不与数字1混淆而没用小写)
(起始值,每次增值,结束时的比较值)相当于一个等差数字序列,从“起始值”的数字开始,每次增加多少(也可设定为负数)为“每次增值”,并与“结束时的比较值”比较,超出则退出for循环(也不执行本轮后面的do 命令)
例如 (1,1,3) 将产生序列 (1 2 3);(1,2,9)将产生序列(1 3 5 7 9);(5,-1,1) 将产生序列 (5 4 3 2 1);(1,3,18)将产生序列(1 7 10 13 16)
例5
@echo off
::在D盘建立aa1~ aa5五个文件夹
for /L %%i in (1,1,5) do md d:\aa %%i
pause
注:在行首,单个冒号:接一名称,是标号行,对应于批处理中go后指向的位置,而双冒号::一般是用来作注释用,注释在批处理中可以用rem加空格来表达,二者稍有不同,rem注释在未关闭命令回显时会在屏幕显示出来,而::则什么情况下都不会显示。
四、参数 /f
这个参数/f将会打开(集)里的文件,使for命令能处理文本文件的读取和添加删除替换等编辑性的操作,可谓功能强大,因此也相对复杂一些。
文件名-集
for /f “选项” %变量 in ( “字符串”-集 ) do 命令
‘命令’-集
/f 后可以带有几种选项,不带选项当然也是合格的格式,而带有参数则必须以引号整体括起来,后面的集里主要由三种形式形成的,最终在for循环中的每一轮中会形成读取一行字符串,来给指定的%变量、以及给由于选项中派生出附加变量赋值后,执行do后面的命令
下面以例子来具体说明和逐步理解各分项的用法
例6
假定d:\abc.txt内容如下:
姓名 性别 年龄 等-级
张三 男 36 A-1
李四 男 29 B-2
赵六 女 31 A-2
执行如下命令:
for /f %c in (d:\abc.txt) do @echo %c
则屏幕上显示:
姓名
张三
李四
赵六
解释:这是for /r 在“%变量”前缺省参数选项时的情况,循环中每轮会默认以空格为分隔,在打开的文件中逐行给字符串分段,又因为没给增添附加变量(即仅一个变量%c)则仅把第一段的字符赋给%c,再执行 do后的命令,然后进行循环的下一轮,并且默认忽略空行
改一下:
for /f “skip=1 tokens=1,4 delims= ” %c in (d:\abc.txt) do @echo %c %d
显示为:
张三 A-1
李四 B-2
赵六 A-2
解:
skip=1 表示文本开始忽略的行数为1 ——忽略几行
delims= 在一行中,用什么单个符号(可以有多字符组合,之间也不能加空格,被理解为多项单个字符,如要空格符须放最后)来分隔字符串作为读取赋值的单元(形成一段),本例中等号后是空的表示仅用空格来分隔。——用什么刀来切分
tokens=1,4 这个等号后的数字表示依次取第几个被分隔的字符串段,来分别赋给%变量及顺序附加的变量,本例取第1个段赋给%c,第4个段赋给c后的一个变量也就是赋给%d,并且,可以写成tokens=1,2,5-7 或tokens=1,2,3* 或tokens=1,2,5,7 分别表示取第1,2,5,6,7(依次赋给%c, %d, %e, %,f, %g共5个变量)、1,2,3及3后的所有段(要赋给3个变量)、1,2,5,7(要赋给4个变量),tokens=后的数字号可以不按顺序,但书写的顺序与分配给变量的顺序是对应的,这是赋值,至于之后do命令中用不用是另一回事。换句话 --——最多只需取哪几段
in (变量) 中的那个变量,代表起始的一个变量名,按tokens中定义的总个数来扩充附加变量名,如总个数为3,则%c 就附加%d和%e ,要是%C就附加%D%E… 本例中tokens=1,4仅需两个,起始的是in () 括号中的%c 则每行中第一段赋给%c,第4段赋给变量%d
以第二行(第一行被skip=1跳过了)为例,在 “张三 男 36 A-1 ” 中(正好也是用的空格分隔)共被空格之刀切为五段,只要第1、4,即张三赋给%c, A-1赋给%d,执行@echo %c %d然后下一轮…而空行照旧被省去了。
再稍改一下:
for /f “skip=1 tokens=4,1 delims=- “ %c in (d:\abc.txt) do @echo %c %d
则显示为:
A 张三
B 李四
A 赵六
例7
假定d:\aa.txt内容如下:
Volume in drive D is MYDA
Volume Serial Number is C35D-8998
Directory of D:tmp
09/25/2001 10:40 AM 11,235 yg0925.txt
11/12/2001 04:29 pM 795 buple.txt
04/11/2002 04:18 AM 2,043 vitn.txt
3File(s) 12,673 bytes
0 Dir(s) 5,020,200,655 bytes free
在命令行输入:
for /f "skip=5 tokens=5" %a in (d:\aa.txt) do @echo %a
会显示:
yg0925.txt
buple.txt
vitn.txt
free
本意想把文件里列出的文件显示出来(当然也可以换成对文件进行其他命令操作)
通过skip=5 忽略掉前5行,默认以空格分隔后tokens=5取每行第五段字符就顺利地把文件名赋给变量%a,美中不足最后一行取了个不是文件名的(当然可用其他方法处理这个多余的只是for/f中没提供忽略最后几行的格式),而倒数第二行则无第五段。
显然例中aa.txt里的内容是某次执行dir命令后的内容。它可用类似命令:
dir > d:\aa.txt来建立
题外话,如果在dir中加入合适的参数/b,就可以回避多余的部分,还可加入/ad只显示目录,加入/a-d只显示文件等
那么,我们完全可以直接书写命令放入in后的(‘命令’-集)中
for /f "skip=5 tokens=5 " %a in ('dir') do @echo %a
效果一样。
注:命令集需用单引号括起来以表示不是文件集,如用双引号括起来则表示是字符串集,本例是为了说明for命令的用法,真正有这种用途也愿意用前面“题外话”的方法。如果你在执行本例后什么也没显示,你需要先用集里的命令先执行一次,看它显示的格式,也许需要把tokens=5 改成tokens=4 或许还应当给dir加上参数 /a-d以回避显示出目录。
如果集里是由多个文件组成,那么处理完一个文件后又处理完又去处理另一个文件,每个文件行数不同循环次数(do命令的次数)也将因此不同。
如果集里是由命令产生的系统,那么你必须首先熟悉该命令执行后会产生怎样效果的字符系统,才能正确安排后面的do命令
画龙点睛:无论in后的集是哪种形式,for/f 都最终分解为字符串,按需要是否“忽略几行”(skip=)、“用什么刀来切分”(delims= )、“最多只需取哪几段”(tokens=)将集里形成的字符串,逐行地分段赋给%或%%后的变量及可能顺延扩展出的变量,以执行do后的命令,每一行即为一轮循环。这里没完整说明全部参数,请在命令行用for/?查看。(下面的斜体字是复制的帮助里的内容)
例如:
对于带有空格的文件名,您需要用双引号将文件名括起来。为了用这种方式来使用双引号,您还需要使用 usebackq 选项,否则,双引号会被理解成是用作定义某个要分析的字符串的。——换句话说,带有usebackq(放在for /f 之后的引号里)参数时 in ()里用双引号表示的仍是文件名。
还有一个选项eol= :前面所说skip=是表示忽略开始的几行,其实默认状况还忽略所有分号“ ; ”开始的行,如果你想不忽略分号开始的行,或者想忽略自己指定一字符开始的行就可以在for /f 之后那引号参数里使用eol=你自己定义的字符,但它不像delims=的那样可定义多个,只允许定义一个。
另一花样:可以用 %~ 操作符将文件名分离成文件名、扩展名、盘符等独立部分 ,请看for/?中的解释(其中示例的变量为%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
简记:凡是 %~ 打头的操作符,都是文件名或环境变量的分离操作。而每项要想运用自如,则需要付出辛勤的练习。
练习:(我偷点懒,自己不作了...)
遍历C、D盘,查找已知文件名(接收键盘输入),把其存放位置、时间,记录到D:\mynote.txt 记录格式如:
xx年xx月xx日 经查找在C盘、D盘的xx文件情况如下:
时间 位置
。。。。。 。。。。。。
。。。。。 。。。。。。
。。。。。 。。。。。。
。
。
。
提示:可能用到的DOS命令、变量、参数: echo、set 、set/p 、%date%、%~ >、>>
总结及提示:
for 命令的实际用法基本上已终结,但是仅此是不能写出强大功能的批处理的,它只是一条DOS命令,需要熟练一些其他的DOS命令和Windows系统提供的命令,组合运用,才能充分发挥其强大、实用的功能,使得一些复杂事情,处理起来意想不到的简洁方便。
附:常见在批处理for命令中需要的一个的命令或者叫环境设置:
for命令实际上是会作循环,如果在每轮的命令中改变某环境变量值,在默认状态,一条for命令用%环境变量%只取一次值的,那么下轮循环中再用时还是改变前的值(包括do后面带有括号里的多条命令的执行期间),就没达到预期目的,为此,引入下面命令:
setlocal enabledelayedexpansion
开始批处理文件中环境改动的本地化操作,并启动延缓环境变量扩展。在执行SETLOCAL 达到批处理文件结尾时,对于该批处理文件的每个尚未执行的 setlocal 命令,都会有一个隐含的 endlocal 被执行。
在取变量值时,用!变量名!可以动态取值,延迟环境变量扩充允许您使用一个不同的字符(惊叹号)在执行时间扩充环境变量。这个用法实际是属于在批处理中所有复合型命令都需要注意的。如果批处理结束后不希望将改变的环境保留,建议总是加上setlocal 。
要是结合一些其他复杂些的有关系统的、网络的命令(如wmic、net)进来,那才是方显FOR英雄本色,比如遍历本地磁盘可以用命令:wmic logicaldisk where "drivetype=3" get name 显然要在所有磁盘里查找某文件并作相应操作就很容易了,用好for命令也是需要其他命令和计算机基础配合的。呵呵,本人水平有限,写的只是低级层次的...但愿能对有缘来这里看的初学DOS的FOR命令者有所帮助。
转自csdn ,原网址:
https://blog.csdn.net/houkai6/article/details/8514336
The FOR command is a command that runs in the command line or batch processing to sequentially loop through a series of objects and execute the same or multiple commands. When combined with some programs in Windows management, its processing function is powerful, and its flexible and convenient application is impressive. However, its help information is also complex, often intimidating beginners. Here, based on my learning and understanding, I decompose and simplify its usage. Omissions and errors may be inevitable.
Basic format
(What is written here is the format used in the command line. If it is in a batch processing, you need to add an additional % in front of % to form %%):
for /parameter %variable in (set) do command
(Note: Except for the Chinese parts above, the rest are written according to its format requirements, and case does not matter)
Parameters: FOR has four types of parameters D L R F, and some parameters can also be attached with additional options, which will be introduced separately below.
Variable: (Remember that when using the FOR command in batch processing, the % in front of the variable should be changed to %%). This variable name is composed of a single letter and is case-sensitive (the original help says so. In actual application, it has been proved that using a single number as the variable name is also feasible), such as %B and %b represent different variables. The FOR command will assign the value read from in (set) to this variable in each loop, so that it can be referenced in subsequent commands.
Set: A set formed by a series of files, strings, or content generated by commands (of course, wildcards *? can be used, and environment variables can also be referenced). The FOR command reads the content in the set in a certain order and rule, assigns it to the variable, and executes the command after do, and then loops to the next round until the content in the set is read. The parentheses are necessary for the format (there should be a space between in and the following parentheses).
Command: 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 to be executed in one loop.
Note: Since some directories or file names may have spaces, in many cases, English quotes are often needed to enclose the content in the set and the command to indicate that it is a whole (but sometimes the content in the quotes may be regarded as a string). For the sake of brevity, the situation where the file name or directory name has spaces is ignored in some examples below.
Now, examples are explained by classifying parameters:
1. Parameter /d
for /d %%variable in (set) do command
The /d parameter specifies a FOR command that only operates on directories, not files.
Example 1:
Enter in the command line (not in batch processing, no more explanation later)
for /d %a in (c:\*.*) do echo %a
Running this will display all directories under the root directory of drive C one by one, and not display file names.
It looks a bit messy. If the command prompt echo is turned off, it will be clear:
for /d %a in (c:\*.*) do @echo %a
2. Parameter /R
The /R parameter can also be followed by a drive letter and path
for /r %variable in (set) do command
The path after /r refers to the entire directory tree under it (equivalent to the range in the DOS command tree). If it is only a single English period ., it refers to the directory tree under the current path. If the path is omitted, it specifically refers to the current directory. The in (set) later is equivalent to the file set matching each previous directory.
Here, it is divided into two cases according to whether there are wildcards in in (set)
1) There are no wildcards in in (set)
Specifies a single file or listed specific files (multiple file names are separated by separators such as spaces, commas, etc.)
Example 2
@echo off
for /r . %i in (abc.txt) do echo. > %i
echo on
Note: The path after for /r here is only a ., and echo. > %i in each subsequent loop is equivalent to creating a text file with only an empty line. The overall effect is to create an abc.txt in each directory under the current directory including subdirectories.
Example 3 (put in batch processing)
@echo off
rem Display the list of files named file1 and file2 in drive d:
for /r d:\ %%h in (file1,file2) do if exist %%h echo %%h
pause
2) There are wildcards * or? in in (set)
The do command here will process each item in the directory series specified by /r that contains the file in the in (set), and ignore those directories that do not contain matching files.
Example 4:
@echo off
rem Delete all *.chk files in drive c:
for /r c:\ %%h in (*.chk) do del /q %%h
pause
Note: del /q means delete in quiet mode (no confirmation is required)
3. Parameter /L
for /L %%variable in (start value, increment each time, comparison value at the end) do command
(The above L can also be in lowercase, mainly to avoid confusion with the number 1 visually, so it is not in lowercase)
(start value, increment each time, comparison value at the end) is equivalent to an arithmetic sequence of numbers. It starts from the number of "start value", increases by how much each time (can also be set to a negative number), and compares with the "comparison value at the end". If it exceeds, the FOR loop exits (and the do command for this round is not executed).
For example, (1,1,3) will generate the sequence (1 2 3); (1,2,9) will generate the sequence (1 3 5 7 9); (5,-1,1) will generate the sequence (5 4 3 2 1); (1,3,18) will generate the sequence (1 7 10 13 16)
Example 5
@echo off
:: Create five folders aa1~aa5 on drive d:
for /L %%i in (1,1,5) do md d:\aa %%i
pause
Note: A single colon : followed by a name at the beginning of a line is a label line, corresponding to the position pointed to by go in batch processing. The double colon :: is generally used for comments. Comments in batch processing can be expressed by rem plus a space. There is a slight difference. The rem comment will be displayed on the screen when the command echo is not closed, while :: will not be displayed in any case.
4. Parameter /f
This parameter /f will open the file in (set) so that the FOR command can process the reading and editing operations such as adding, deleting, and replacing of text files, which is very powerful, so it is relatively complicated.
File name - set
for /f "options" %variable in ("string" - set) do command
'Command' - set
Several options can be carried after /f. It is a qualified format without options. If parameters are carried, they must be enclosed in quotes as a whole. The set later is mainly formed by three forms. Finally, in each round in the FOR loop, a line of string will be formed to assign values to the specified %variable and additional variables derived from the options, and then execute the command after do.
The following uses examples to specifically explain and gradually understand the usage of each sub-item.
Example 6
Assume that the content of d:\abc.txt is as follows:
Name Gender Age Grade
Zhang San Male 36 A-1
Li Si Male 29 B-2
Zhao Liu Female 31 A-2
Execute the following command:
for /f %c in (d:\abc.txt) do @echo %c
Then the screen will display:
Name
Zhang San
Li Si
Zhao Liu
Explanation: This is the situation when %variable in for /r has no default parameter options. In each round of the loop, it will default to using spaces as separators, segment the lines in the opened file one by one. And because no additional variables are added (that is, only one variable %c), only the characters of the first segment are assigned to %c, then the command after do is executed, and then the next round of the loop is carried out, and empty lines are ignored by default.
Change it:
for /f "skip=1 tokens=1,4 delims= " %c in (d:\abc.txt) do @echo %c %d
Display as:
Zhang San A-1
Li Si B-2
Zhao Liu A-2
Explanation:
skip=1 means ignoring 1 line at the beginning of the text - ignoring several lines
delims= In a line, use what single symbol (can be a combination of multiple characters, no spaces between them, which are understood as multiple single characters. If a space character is needed, it must be placed at the end) to separate the string as the unit for reading and assignment (forming a segment). In this example, the empty after the equal sign means using only spaces to separate. - What knife to use to cut
tokens=1,4 The number after this equal sign means taking the first and fourth separated string segments in turn to assign to the %variable and the subsequent additional variables respectively. In this example, the first segment is assigned to %c, and the fourth segment is assigned to a variable after c, that is, assigned to %d. Moreover, it can be written as tokens=1,2,5-7 or tokens=1,2,3* or tokens=1,2,5,7, which respectively mean taking the 1st, 2nd, 5th, 6th, 7th (assigned to %c, %d, %e, %,f, %g in turn for 5 variables), 1st, 2nd, 3rd and all segments after 3rd (to assign to 3 variables), 1st, 2nd, 5th, 7th (to assign to 4 variables). The numbers after tokens can be out of order, but the writing order corresponds to the order of assigning to variables. This is assignment. As for whether to use it in the do command later is another matter. In other words -- the maximum number of segments to take.
The variable in (variable) represents the starting variable name. According to the total number defined in tokens, additional variable names are expanded. For example, if the total number is 3, then %c is additionally %d and %e. If it is %C, then %D%E... is additionally. In this example, tokens=1,4 only needs two. The starting one is %c in the parentheses of in (), so the first segment in each line is assigned to %c, and the fourth segment is assigned to variable %d.
Take the second line (the first line is skipped by skip=1) as an example. In "Zhang San Male 36 A-1" (also separated by spaces), it is cut into five segments by the knife of spaces. Only the 1st and 4th are needed, that is, Zhang San is assigned to %c, and A-1 is assigned to %d. Then @echo %c %d is executed, and then the next round... and empty lines are still omitted.
Change it a little more:
for /f "skip=1 tokens=4,1 delims=- " %c in (d:\abc.txt) do @echo %c %d
Then it will display:
A Zhang San
B Li Si
A Zhao Liu
Example 7
Assume that the content of d:\aa.txt is as follows:
Volume in drive D is MYDA
Volume Serial Number is C35D-8998
Directory of D:tmp
09/25/2001 10:40 AM 11,235 yg0925.txt
11/12/2001 04:29 pM 795 buple.txt
04/11/2002 04:18 AM 2,043 vitn.txt
3File(s) 12,673 bytes
0 Dir(s) 5,020,200,655 bytes free
Enter in the command line:
for /f "skip=5 tokens=5" %a in (d:\aa.txt) do @echo %a
It will display:
yg0925.txt
buple.txt
vitn.txt
free
Originally, I wanted to display the files listed in the file (of course, other commands can also be used to operate on the files). By skipping the first 5 lines with skip=5, and taking the fifth segment of each line after defaulting to separating by spaces with tokens=5, the file name is smoothly assigned to variable %a. The only drawback is that the last line takes a non-file name (of course, other methods can be used to handle this redundant one, but the format to ignore the last few lines is not provided in for/f). And the second last line has no fifth segment.
Obviously, the content in example aa.txt is the content after executing the dir command at a certain time. It can be established by using a similar command:
dir > d:\aa.txt
By the way, if appropriate parameters are added in dir /b, the redundant part can be avoided, and /ad can be added to only display directories, and /a-d can be added to only display files, etc.
Then, we can directly write the command and put it in the ('command' - set) after in.
for /f "skip=5 tokens=5 " %a in ('dir') do @echo %a
The effect is the same.
Note: The command set needs to be enclosed in single quotes to indicate that it is not a file set. If it is enclosed in double quotes, it indicates that it is a string set. This example is to illustrate the usage of the FOR command. If there is really such a use, the method in the "By the way" is also willing to be used. If nothing is displayed after you execute this example, you need to execute the command in the set first to see the format it displays. Maybe tokens=5 needs to be changed to tokens=4, and maybe the dir needs to be added with parameter /a-d to avoid displaying directories.
If the set is composed of multiple files, then after processing one file, it will process another file, and the number of loops (the number of times the do command is executed) will also be different due to different number of lines in each file.
If the set is composed of the system generated by commands, then you must first be familiar with the character system produced by the execution of the command, so as to correctly arrange the do command later.
The finishing touch: No matter what form the set after in is, for/f finally decomposes it into strings. According to whether "ignore several lines" (skip=), "use what knife to cut" (delims=), "take up to which segments" (tokens=), the strings formed in the set are segmented line by line and assigned to the variables after % or %% and possibly extended variables, so as to execute the command after do. Each line is a round of loop. This does not fully explain all parameters. Please use for/? in the command line to view. (The italicized words below are copied from the help content)
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, the double quotes will be understood as defining a string to be analyzed. - In other words, when the usebackq (placed in the quotes after for /f) parameter is carried, the double quotes in in () still represent the file name.
There is another option eol=: The skip= mentioned above means ignoring the first few lines. In fact, by default, all lines starting with the semicolon ";" are also ignored. If you don't want to ignore the lines starting with semicolons, or want to ignore the lines starting with your own specified character, you can use the eol= your own defined character in the quotes after for /f. But it is not like delims= that can define multiple, only one can be defined.
Another trick: You can use the %~ operator to separate the file name into independent parts such as file name, extension, drive letter, etc. Please see the explanation in for/? (where the example variable is %I):
In addition, the replacement of FOR variable references has been enhanced. You can now use the following option syntax:
~I - Remove any quotes ("), expand %I
%~fI - Expand %I to a fully qualified path name
%~dI - Only expand %I to a drive letter
%~pI - Only expand %I to a path
%~nI - Only expand %I to a file name
%~xI - Only expand %I to a file extension
%~sI - The expanded path only contains short names
%~aI - Expand %I to the file attributes of the file
%~tI - Expand %I to the date/time of the file
%~zI - Expand %I to the size of the file
%~$PATH:I - Find the directory listed in the path environment variable and expand %I to the first fully qualified name found. If the environment variable name is not defined or the file is not found, this combination key will expand to an empty string.
You can combine modifiers to get multiple results:
%~dpI - Only expand %I to a drive letter and path
%~nxI - Only expand %I to a file name and extension
%~fsI - Only expand %I to a full path name 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 - Expand %I to a DIR-like output line
Brief summary:凡是 %~ 打头的操作符,都是文件名或环境变量的分离操作。而每项要想运用自如,则需要付出辛勤的练习。
Practice: (I'm lazy, I won't do it myself...)
Traverse drives C and D, find the known file name (receive keyboard input), record its storage location and time in D:\mynote.txt. The record format is as follows:
XX year XX month XX day. After searching, the situation of file XX on drives C and D is as follows:
Time Location
...... ......
...... ......
...... ......
.
.
.
Tip: The DOS commands, variables, and parameters that may be used: echo, set, set/p, %date%, %~ >, >>.
Summary and tips:
The actual usage of the FOR command has basically ended, but this alone cannot write a powerful batch processing. It is only a DOS command. You need to be proficient in some other DOS commands and commands provided by the Windows system, and combine them to give full play to its powerful and practical functions, so that some complex things can be handled unexpectedly simply and conveniently.
Attachment: A common command or environment setting needed in the batch processing FOR command:
The FOR command actually loops. If the value of an environment variable is changed in the command of each round, in the default state, a FOR command uses %environment variable% to get the value only once, then when it is used again in the next round of the loop, it is still the value before the change (including during the execution of multiple commands in parentheses after do), which does not achieve the expected purpose. Therefore, the following command is introduced:
setlocal enabledelayedexpansion
Start the localization operation of environment changes in the batch processing file and start delayed environment variable expansion. When the end of the batch processing file is reached for EXECUTING SETLOCAL, there will be an implicit endlocal for each setlocal command of the batch processing file that has not been executed yet.
When getting the variable value, using!variable name! can get the value dynamically. Delayed environment variable expansion allows you to use a different character (exclamation mark) to expand the environment variable at execution time. This usage actually belongs to what all compound commands in batch processing need to pay attention to. If you do not want to retain the changed environment after the batch processing ends, it is recommended to always add setlocal.
If combined with some other more complex commands related to the system and network (such as wmic, net), then it is the time to show the heroism of FOR. For example, traversing local disks can use the command: wmic logicaldisk where "drivetype=3" get name. Obviously, it is very easy to search for a certain file in all disks and perform corresponding operations. Using the FOR command well also requires cooperation with other commands and computer basics. Hehe, my level is limited, and what I write is only at a low level... I hope it can help those who are learning the FOR command of DOS.
Transferred from CSDN, original website:
https://blog.csdn.net/houkai6/article/details/8514336