简体   繁体   中英

How to get previous (nth) of last modified file in batch

Say in a folder I have 5 files ABCD E. I need to find last modifed which is D and the previous one C or may be nth previous. How to do that?

I got last modified : http://blogs.msdn.com/b/oldnewthing/archive/2012/08/01/10334557.aspx

but not the nth one which is more generic.

@echo off

set "root_dir=c:\somewhere"
pushd "%root_dir%"
set "bl1="
set "bl2="

setlocal enableDelayedExpansion
for /f "tokens=* delims=" %%# in ('dir /b /a:-d /o:d') do (
    set "bl2=!bl1!"
    set "bl1=%%#"
)

echo %bl2%

endlocal
@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET /a skiplength=%1
IF %skiplength%==0 (SET "skiplength=") ELSE (SET "skiplength=skip=%skiplength%")
FOR /f "%skiplength%delims=" %%a IN (
  'dir /b /a-d /o-d "%sourcedir%\*" '
  ) DO ECHO %%a&GOTO done
:done


GOTO :EOF

Where the first parameter provided is the n'th (0=leatest, 1=second-latest) etc.

It simply builds skiplength as nothing or skip=$required depending on the number entered then executes a directory-list excluding the directorynames (/ad) and in reverse-date order (/od); skips the required number of entries, produces one line of output and jums out of the loop.

Choice of sourcedir is up to you. Naturally, you could assign %%a to a variable if you so desired.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM