I am using dir abc*.*/o:-d/b >> "testfile1.txt"
to get the output in descending order. Is there a way to get only 5 / 10 files as output. Actually I want to store the latest 5 (sorted by Date Modified) files in testfile1.txt.
Appreciate your response
@echo off
setlocal
set /a "n=0, limit=5"
>"testfile1.txt" (
for /f "eol=: delims=" %%F in ('dir /o-d /b abc*.*') do (
echo %%F
2>nul set /a "n+=1, 1/(limit-n)"||goto :break
)
)
:break
I intentionally divide by 0 to detect when the limit has been reached. I could simply use an IF statement instead, but that would require delayed expansion, and delayed expansion would corrupt a file name that contains !
. A proper solution with delayed expansion must toggle delayed expansion on and off within the loop.
I know I'm a little late on this one, but how about this instead:
@echo off
for /f "tokens=1* delims=:" %%a in ('dir abc*.*/o:-d/b ^| findstr /n .') do if %%a leq 5 echo.%%b>>"testfile1.txt"
Here's what I did to make this work:
Edit: changed 'findstr /n .*' to 'findstr /n .', as there are no empty lines too watch out for (see comments below).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With