[英]Windows 7 Batch File for loop
In both cases the directory contains three files named test1.txt, test2.txt, test3.txt 在这两种情况下,该目录包含三个名为test1.txt,test2.txt,test3.txt的文件
Can someone explain why this works: 有人能解释为什么这样有效:
echo off
set CP=
for %%f in (*.txt) do (
call :concat %%f
)
echo %CP%
:concat
set CP=%CP%;%1
output: 输出:
C:\test>test
C:\test>echo off
;test1.txt;test2.txt;test3.txt
C:\test>
But this does not: 但这不是:
echo off
set CP=
for %%f in (*.txt) do (
set CP=set CP=%CP%;%%f
)
echo %CP%
output: 输出:
C:\test>test
C:\test>echo off
;test3.txt
C:\test>
It has to do with Delayed Expansion. 它与延迟扩展有关。
For example, this will work just like your first example: 例如,这将像您的第一个示例一样工作:
echo off
SETLOCAL EnableDelayedExpansion
set CP=
for %%f in (*.txt) do (
set CP=!CP!;%%f
)
echo %CP%
ENDLOCAL
When Delayed Expansion is enabled then variables surrounded with !
启用延迟扩展时,变量包围
!
are evaluated on each iteration instead of only the first time when the loop is parsed (which is how variables surrounded with %
are parsed). 在每次迭代时评估,而不是仅在解析循环时第一次(这是解析用
%
包围的变量的方式)。
Your first example works because the processing is done in a CALL
statement which passes control to another segment of the batch file which is technically outside the loop so it is parsed individually each time it is executed. 您的第一个示例有效,因为处理是在
CALL
语句中完成的,该语句将控制权传递给批处理文件的另一个段,该段在技术上位于循环之外,因此每次执行时都会对其进行单独解析。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.