MS DOS script in DIR only the first 10 files, descending

I use 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 save the latest files (sorted by date) in the testfile1.txt file.

Rate your answer

+4
source share
3 answers
 @echo off setlocal set /a "n=0, limit=5" >"testfile1.txt" ( for /f "eol=: delims=" %%F in ('dir /od /b abc*.*') do ( echo %%F 2>nul set /a "n+=1, 1/(limit-n)"||goto :break ) ) :break 

I intentionally divide by 0 to determine when the limit is reached. I could just use the IF statement instead, but that would require a delayed extension, and a slow extension would distort the filename containing ! . The correct solution with expansion delay should turn on and off slow expansion within the loop.

+7
source

I know that I'm a little late for this, but what about this:

 @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 is what I did to make this work:

  • Configured your dir statement in findstr for each line number ( dir abc *. * / O: -d / b | findstr / n. )
  • Drop it through a for loop a separate line # from the content (using "tokens = 1 * delims =" )
  • The if statement used to check the current line # is less than or equal to "5" ( if %% a leq 5 ... )
  • All lines corresponding to the specified file are exported ( echo. %% b → "testfile1.txt" )

Edit: changed findstr / n. * 'before findstr / n. 'since there are no empty lines. (see comments below).

+3
source

Should it be a batch file? That would be trivial in PowerShell.

To do this with plain old batch files, you will need something similar to a head utility to capture only the first few lines of output.

You can adapt the solution here according to your needs (pay attention to the section in the answer about a small "winhead.cmd" script): Batch command to enter only the first line of input

0
source

All Articles