Page 1 of 1

Get latest 2 files in directory

Posted: 13 Aug 2018 14:04
by SIMMS7400
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?

Re: Get latest 2 files in directory

Posted: 13 Aug 2018 14:54
by aGerman

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

Re: Get latest 2 files in directory

Posted: 16 Aug 2018 12:59
by SIMMS7400
Hi Steffen -

Thank you so much - this is working great!