Search code examples
windowsbatch-filecmddirectorycommand

Find the most recently modified file with a specific extension in a directory


I am trying to write a Windows batch file to find the most recent *.CPP file in a directory.

To find the most recent file in the current directory, this works:

@echo off
for /F "delims=" %%f in ('dir   /b /od /a-d "%*" ') do set File=%%f
echo %*\%File%
pause

But it only shows me the most recent file of the directory

I want to focus only on *.CPP files, among all of the files in the directory.

If it's not possible perhaps a method of excluding *.TXT, *.BAT and *.EXE files from the DIR command, *(because it's mainly those 3 kinds of files that always have more recent modified date compared to my cpp files.


Solution

  • oh, i notice a very useful comment from Stephan from my previous question here few days ago : search CMD on internet search engines instead of DOS

    and miracle my duckduckgo found this : Get newest file in directory with specific extension

    so here is the answer ! (credit to Mofi)

    FOR /F "eol=| delims=" %%I IN ('DIR *.CPP /A-D /B /O-D /TW 2^>nul') DO (
    SET NewestFile=%%I
    GOTO FoundFile
    )
    ECHO No *.CPP file found!
    GOTO :EOF
    
    :FoundFile
    ECHO Newest *.CPP file is: %NewestFile%
    
    pause
    

    if someone needs the same code to find other specific newest file in directory just change the three CPP arguments by what you need

    I just realize that the information I need is not only to ECHO of the name of the most recent CPP file in the directory, but also its date, if I find how to do I will update it here, if not help is still needed here ^^ EDIT: ok found it again thanks to this ♥awesome website♥

    FOR /F "eol=| delims=" %%I IN ('DIR *.CPP /A-D /B /O-D /TW 2^>nul') DO (
    SET NewestFile=%%I
    SET NewestFileDate=%%~tI
    GOTO FoundFile
    )
    ECHO No *.CPP file found!
    GOTO :EOF
    
    :FoundFile
    ECHO Newest *.CPP file is: %NewestFile% %NewestFileDate%
    
    pause
    

    CMD batch files are very interesting!!! but also very time consuming to know how to write them correctly when we are novice ^^