Get latest 2 files in directory

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
SIMMS7400
Posts: 446
Joined: 07 Jan 2016 07:47

Get latest 2 files in directory

#1 Post by SIMMS7400 » 13 Aug 2018 14:04

Hi Folks -

I have a need to grab the names of the (2) NEWEST files in a particular directory. To grab one file name, I'm using the following with success :

Code: Select all

FOR /F "delims=" %%a IN ('DIR "%OD_CMSO_OPEX_BIN%%%~A*.csv" /B /OD /A-D') DO SET "LATEST=%%~a"
My thought is to find the latest then move it to a temp directory, then rerun the above line again to grab the latest. Thoughts?

aGerman
Expert
Posts: 3706
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Get latest 2 files in directory

#2 Post by aGerman » 13 Aug 2018 14:54

Code: Select all

for /f "tokens=1* delims=:" %%a in ('dir /a-d /b /o-d "%OD_CMSO_OPEX_BIN%%%~A*.csv"^|findstr /n "^"') do if %%a lss 3 move "%%b" "somewhere\else\"
DIR /O-D sorts descending and thus, the newest files are first. FINDSTR /N prepends the line number followed by a colon to each line. The TOKENS and DELIMS options make that the line number is in %%a and the file name is in %%b. The IF statement lets only the file names pass through where the line numbers were less than three.

Steffen

SIMMS7400
Posts: 446
Joined: 07 Jan 2016 07:47

Re: Get latest 2 files in directory

#3 Post by SIMMS7400 » 16 Aug 2018 12:59

Hi Steffen -

Thank you so much - this is working great!

Post Reply