Windows 7循环批处理文件
在这两种情况下,目录都包含三个名为test1.txt、test2.txt和test3.txt的文件 有人能解释一下为什么会这样:Windows 7循环批处理文件,windows,batch-file,Windows,Batch File,在这两种情况下,目录都包含三个名为test1.txt、test2.txt和test3.txt的文件 有人能解释一下为什么会这样: echo off set CP= for %%f in (*.txt) do ( call :concat %%f ) echo %CP% :concat set CP=%CP%;%1 输出: C:\test>test C:\test>echo off ;test1.txt;test2.txt;test3.txt C:\test>
echo off
set CP=
for %%f in (*.txt) do (
call :concat %%f
)
echo %CP%
:concat
set CP=%CP%;%1
输出:
C:\test>test
C:\test>echo off
;test1.txt;test2.txt;test3.txt
C:\test>
C:\test>test
C:\test>echo off
;test3.txt
C:\test>
但这并不是:
echo off
set CP=
for %%f in (*.txt) do (
set CP=set CP=%CP%;%%f
)
echo %CP%
输出:
C:\test>test
C:\test>echo off
;test1.txt;test2.txt;test3.txt
C:\test>
C:\test>test
C:\test>echo off
;test3.txt
C:\test>
这与延迟扩张有关 例如,这将与您的第一个示例一样工作:
echo off
SETLOCAL EnableDelayedExpansion
set CP=
for %%f in (*.txt) do (
set CP=!CP!;%%f
)
echo %CP%
ENDLOCAL
启用延迟扩展后,变量将被包围代码>在每次迭代时进行计算,而不是仅在第一次解析循环时进行计算(这是解析%
包围的变量的方式)
您的第一个示例之所以有效,是因为处理是在CALL
语句中完成的,该语句将控制传递给批处理文件的另一段,该段在技术上处于循环之外,因此每次执行时都会对其进行单独解析。可能会有所帮助