Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MS DOS script to DIR first 10 files only, descending order

Tags:

batch-file

dos

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

like image 601
user1594788 Avatar asked Dec 20 '22 17:12

user1594788


2 Answers

@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.

like image 80
dbenham Avatar answered Jan 24 '23 10:01

dbenham


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:

  • Piped your dir statement into findstr to number each line (dir abc*.*/o:-d/b | findstr /n .)
  • Ran it through a for loop to separate line #'s from content (using "tokens=1* delims=:")
  • Used an if statement to verify the current line # is less than or equal to "5" (if %%a leq 5...)
  • Exported all lines that match to the file you specified (echo.%%b>>"testfile1.txt")

Edit: changed 'findstr /n .*' to 'findstr /n .', as there are no empty lines too watch out for (see comments below).

like image 23
Seth McCauley Avatar answered Jan 24 '23 09:01

Seth McCauley