3

I have a problem here. First things first, the code:

Contents of 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 ------------------

In the same directory where test.bat is, there are two test files: 1.txt and 2.txt

When I run test.bat, my output is:

------------------
2.txt
2.txt
------------------

As you can see, 1.txt isn't listed.

And when adding a 3.txt, the output is:

------------------
3.txt
3.txt
3.txt
------------------

Can anyone help me please??

Thanks, Andrew Wong

2 Answers 2

5

You'll need to use Delayed Expansion feature, since within a FOR loop, you're reading a variable, and that variable is also modified in that loop.

@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 ------------------
Sign up to request clarification or add additional context in comments.

Comments

3

You could also use a function (subRoutine)... That also "force" CMD to evaluate for each loop...

@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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.