Home > database >  Batch get n most recently modified files without need of multiple FOR loops
Batch get n most recently modified files without need of multiple FOR loops

Time:01-03

As specified in the Question title, I have the following DIR command to get most recently modified files in any directory provided the command or script with this command in running in the same directory whose files list is to be filtered.

dir /b /o:-d

But the quirk here is that I want to limit the number of files in the most-recently-modified files list such that I can run for loop on each. This list needs to be generated without using multiple FOR loops, which I can't think of any way to figure out. I can loop thro' the whole list like below:

for /F "delims=" %%a in ('dir /b /o:-d') do echo %%a

How do I reliably stop this loop strictly when most recent n files are already listed ??

CodePudding user response:

I suggested you could use a prior example and modify it to accept 6 such as below where you can add a number via command line, you attempted to make a change but would be better off using this version with !count! rather than trying %%

Latest.cmd

usage: latest 6

@ECHO OFF
setlocal EnableDelayedExpansion
set "j=0"
set "count=%1"

FOR /f "delims=" %%i IN ('dir /b /a-d /o-d *.*') DO (
    echo %%i
    set /A j=j 1
    if !j! geq !count! (
        goto :end
    )
)
:end

A much simpler version for say 6 files would be a modification to dbenham's answer at https://stackoverflow.com/a/11367577/10802527

@echo off
set n=0
set count=6
for /f "usebackq delims==" %%F in (`dir /b /a-d /o-d *.*`) do (
  echo %%F
  set /a "n =1, 1/(%count%-n)" 2>nul || goto :break
)
:break
set n=
set count=

CodePudding user response:

Another way to do it in a cmd batch-file.

SET "FILECOUNT=6"
powershell -NoLogo -NoProfile -Command ^
    (Get-ChildItem -File ^| Sort-Object -Property LastWriteTime ^| Select-Object -Last %FILECOUNT%).Name
  • Related