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.
CodePudding user response:
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 ^^
CodePudding user response:
Here is another way to accomplish this in a Windows batch-file run by cmd. Change *.txt to *.cpp or whatever you like. If you are on a supported Windows system, PowerShell is available.
@powershell -NoLogo -NoProfile -Command ^
Get-ChildItem -File -Filter *.txt ^| ^
Sort-Object LastWriteTime -Descending ^| ^
Select-Object -First 1 -Property Name,LastWriteTime ^| ^
ForEach-Object { \"Newest .txt file is $($_.Name) at $($_.LastWriteTime)\" }
Example usage:
21:05:48.58 C:\Users\lit\Documents
C:>\src\t\mostrecentfile.bat
Newest .txt file is developer-onboarding.txt at 09/07/2021 10:34:40
