不知道如何很好地解释这一点,所以这是代码
@echo off
set test=0
for /f %%a in (textfile.txt) do (
rem loops five times(5 lines in textfile.txt)
set /a test=test+1
rem Adds 1 to Test
echo %%a
rem Echo's correct line in file
echo %test%
rem Echo's whatever X was before the loop
)
echo %test%
rem Displays the correct value of X
pause
这只是我发现问题的一个例子,txtfile.txt 有 5 行,因此 for 循环进行 5 次,每次 test 都会对其+1,并且 /a 显示正确的 X 值,但是for 循环上的最后一个 echo 显示 0,这是循环之前设置的 test。
在循环完成之前, test 的值不会改变...有什么方法可以解决这个问题吗?
这就是我想要完成的任务,因为可能有一种更简单的方法:我想运行一个 for 循环,在一系列子文件夹中查找 str 的所有 rtf,并将它们全部复制到新名称 1.rtf 的 all 目录中,2.rtf,3.rtf 等。我需要在传输时重命名它们的原因是它们都具有相同的名称。
Lucero https://stackoverflow.com/questions/980718/cmd-for-loop-does-not-hold-set-a-value/980778#980778是对的。
示例代码:
@echo off
setlocal enabledelayedexpansion
echo.
set numLines=0
echo examining file '%~f0'
echo.
rem loop N times, once for each line in the file
for /f %%a in (%~f0) do (
rem add 1 to the numLines variable
set /a numLines=!numLines!+1
rem echo the first symbol from the line
echo line !numLines!: %%a
)
rem Display the number of lines in the file
echo.
echo The file '%~f0' has %numLines% lines.
echo.
pause
echo.
endlocal
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)