For loop 批处理文件,用于循环不回显行

For loop 批处理文件,用于循环不回显行,for-loop,batch-file,cmd,command-prompt,For Loop,Batch File,Cmd,Command Prompt,我这里有个问题。 首先,代码: test.bat的内容: @echo off cls for /F "delims=" %%a in ('dir /B /A-D ^| findstr /I ".txt$"') do ( set str=%%a echo %str% >> list.tmp pause ) echo ------------------ for /F %%i in (list.tmp) do echo %%i del list.tmp echo -----------

我这里有个问题。 首先,代码:

test.bat的内容:

@echo off
cls
for /F "delims=" %%a in ('dir /B /A-D ^| findstr /I ".txt$"') do (
set str=%%a
echo %str% >> list.tmp
pause
)

echo ------------------
for /F %%i in (list.tmp) do echo %%i
del list.tmp
echo ------------------
在test.bat所在的同一目录中,有两个测试文件: 1.txt和2.txt

当我运行test.bat时,我的输出是:

------------------
2.txt
2.txt
------------------
------------------
3.txt
3.txt
3.txt
------------------
如您所见,1.txt未列出

添加3.txt时,输出为:

------------------
2.txt
2.txt
------------------
------------------
3.txt
3.txt
3.txt
------------------
谁能帮帮我吗

谢谢, Andrew Wong

您需要使用延迟扩展功能,因为在
FOR
循环中,您正在读取一个变量,并且该变量也在该循环中被修改

@echo off
setlocal enabledelayedexpansion
cls
for /F "delims=" %%a in ('dir /B /A-D ^| findstr /I ".txt$"') do (
  set str=%%a
  echo !str! >> list.tmp
  pause
)

echo ------------------
for /F %%i in (list.tmp) do echo %%i
del list.tmp
echo ------------------

您还可以使用函数(子例程)。。。这也“强制”CMD为每个循环求值

@echo off
cls
for /F "delims=" %%a in ('dir /B /A-D ^| findstr /I ".txt$"') do (
  call :doOne %%a 
)

echo ------------------
for /F %%i in (list.tmp) do echo %%i
del list.tmp
echo ------------------
goto :EOF

:DoOne
  set str=%1
  echo %str% >> list.tmp
  pause