I understand that there are tons of questions on this site regarding the creation of a batch file that goes through the file in a specified folder and deletes them if it satisfies the condition stated.
However, I would like to tweak that a little bit. In my batch file, I would like to look at a folder, say C:\Dev and get all the files that are within the same month. After getting all those files, I want to sort through all the dates and delete everything except for the latest one. So if I have 5 files for January on that folder with dates January 1, 12, 20, 27, and 30, I would only keep the file dated January 30th and delete all the others.
Is this possible?Answer1:
< lang-dos -->
@ECHO OFF SETLOCAL SET "targetdir=c:\sourcedir" SET "pfname=" PUSHD "%targetdir%" FOR /f "delims=" %%a IN ('dir /b /a-d /o:d "*" ') DO ( SET "fname=%%a" SET "fdate=%%~ta" CALL :process ) POPD GOTO :EOF :process :: reformat date - this depends on yout local date-format. :: YY(YY)MM required - my format is dd/mm/yyyy SET fdate=%fdate:~6,4%%fdate:~3,2% IF NOT DEFINED pfname GOTO nodel IF %fdate%==%pfdate% ECHO DEL "%targetdir%\%pfname%" :nodel SET pfdate=%fdate% SET "pfname=%fname%" GOTO :eof
This should work for you. The required DEL commands are merely
ECHOed for testing purposes. After you've verified that the commands are correct, change
ECHO DEL to
DEL to actually delete the files.
First, the target directory is set up and
pfname is cleared.
PUSHD changes the
current directory until the
POPD is executed
dir command outputs filenames only (
/b), no directory names (
/a-d) in date-order (
/o:d). Each line sets
fname to the filename and
fdate to the filedate.
:process, the date-string is manipulated. I don't know which format you use, but the basic formula is
%variable:~startposition,length% where startposition starts at 0=first character. The idea is to have
fdate in the format
pfname (previos filename) is not set, this is the first file found, so we don't delete that.
For every other file, if the filedate is the same as the previous filedate, then delete the previous filename.
The current filename/date is then recorded as the previous version.