Windows – Cmdline to get latest file on recursive dir command

cmd.exewindows

On my hard disk, I have hundreds subfolders created daily that may contain a specific text file (Tracker.txt).

I would like to create a cmdline or BAT file to get only one result, the latest tracker.txt file, with its full path !

I tried dir /s tracker.txt /OD but the result is not filtered by date.

Thank you!

Best Answer

You can pipe the DIR /B /S /OD "tracker.txt" command results to a temp log file but have it use the FOR loop substitutions to put the date time stamp of each file that matches the name followed by a comma and then the full explicit path and file name (i.e. YYYY-MM-DD hh:mm [AM/PM]).

You then use the SORT command against that file to sort all the lines in that file to a new sorted file but with the newest time stamp file at the bottom of the list.

Lastly, you'd run a final FOR loop through the final file list using the comma as the delimiter and then only setting the iterator variable in that loop to each full explicit path and when it get to the bottom of that list, this is the newest file that is SET last and then you can do something with that last set variable which is the newest file date stamp wise from within all the directories you specify recursively.


Batch Script Example

Be sure to set the value of the SET StartDir= variable to be the root folder where the DIR command starts for finding the files recursively.

@ECHO ON

SET StartDir=C:\Users\User\Desktop\Test

IF EXIST "%temp%\~dir1temp.dat" DEL /Q /F "%temp%\~dir1temp.dat"
FOR /F "TOKENS=*" %%A IN ('Dir /B /S /OD "%StartDir%\tracker.txt"') DO ECHO %%~TA, %%~FPNXA>>"%temp%\~dir1temp.dat"

IF EXIST "%temp%\~dirsorttemp.dat" DEL /Q /F "%temp%\~dirsorttemp.dat"
SORT "%temp%\~dir1temp.dat">>"%temp%\~dirsorttemp.dat"

FOR /F "TOKENS=2 DELIMS=," %%A IN (%temp%\~dirsorttemp.dat) DO (SET File=%%~A)

ECHO %File%
:::<command to do something with %file%>
PAUSE

Further Resources

  • Sort
  • For /F
  • FOR /? (batch substitutions)

    In addition, substitution of FOR variable references has been enhanced.
    You can now use the following optional syntax:
    
    %~fI        - expands %I to a fully qualified path name
    %~tI        - expands %I to date/time of file
    
  • Set
Related Question