Read Bat file to delete files only when younger files are present for understanding the strategy used in the batch file below to delete all ABC_*.CSV
files in current directory except the latest 20 modified (or created) files.
@for /F "skip=20 delims=" %%I in ('dir "ABC_*.CSV" /A-D /B /O-D /TW 2^>nul') do @del "%%I"
So this simple one line batch file keeps the 20 newest ABC_*.CSV
files in current directory and delete all other (older) files matching this pattern. There must be more than %Date%
in file name of each ABC_*.CSV
when being created twice per day. Or is an already existing ABC_%Date%.CSV
file overwritten on existing already and so there are only 10 files for 10 different dates?
The value after FOR option skip=
determines how many of the newest files should be kept. On creating two ABC_*.csv
files per day and keeping the newest 20 files, all files older than 10 days are deleted by this single line batch file. Well, as written in referenced answer, the age of the files does not really matter, just their file sizes and the remaining free disk space. This solution makes sure that at least the latest 20 ABC_*.csv
files are stored on storage media independent on how often they are created and if the creation of the files is really successful every day.
To use the creation date of the file in the directory use:
@for /F "skip=20 delims=" %%I in ('dir "ABC_*.CSV" /A-D /B /O-D /TC 2^>nul') do @del "%%I"
/TW
(write time) is replaced here by /TC
(creation time) in comparison to above command line.
Please note that the creation date does not store when the file itself was created the first time. It stores the time stamp when this file was created first time in this directory. So for example a file with last modification date 2017-12-30 18:24:30 copied from folder X to another folder Y today has the file creation date 2018-01-01 20:59:38 in folder Y while the last modification date is unmodified 2017-12-30 18:24:30 and file creation date of same file in folder X is for example also 2017-12-30 18:24:30. In other words the file in folder Y was created after its contents being last modified.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
Read also the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul
. The redirection operator >
must be escaped with caret character ^
on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir
command line with using a separate command process started in background.