Reputation: 111
I now have a seemingly innocuous requirement to be put in a .bat file ,I am dealing with Batch code for the first time ...found a page here that deals with something similar but it takes the modified date as reference.
In a particular folder X , Delete all files older than N days by parsing through their file name. where file name format is Name_YYYYMMDD.log
But note : 1. Do not want the last modified date as reference (log might have been accessed/modified by other programs/apps) 2.No permission to install other utilities.
EDIT :
Thanks!.
Upvotes: 0
Views: 4341
Reputation: 11
here you have, it will delete file e.g. 20180105.log on January 5, it's working with date format YYYY-MM-DD, for date format MM/DD/YYYY change this delims=/ and check "echo todayDate !todayDate!" for manipulating a b c
cls
@echo off
setlocal EnableDelayedExpansion
for /F "tokens=1-3 delims=-" %%a in ("%date%") do (
set todayDate=%%a%%b%%c
)
rem echo todayDate !todayDate!
for /F "tokens=1-3 delims=_." %%a in ('dir /B /A-D *.*') do (
set /A daysOld=todayDate - "%%a"
if !daysOld! EQU 0 (
echo deleting.. %%a.%%b
echo del %%a.%%b
)
)
Test it and change the echo del %%a.%%b
to del %%a.%%b
Upvotes: 1
Reputation: 67216
The Batch file below convert file date to Julian Day Number, that is a sequential number of days, and use it to know how many days old is each one. The number of days to delete files is given in the parameter.
@echo off
setlocal EnableDelayedExpansion
rem Get Julian Day Number of today's date
rem The assumed format is MM/DD/YYYY, change C-A-B order in accordance with your locale
for /F "tokens=1-3 delims=/" %%a in ("%date%") do (
set todayDate=%%c%%a%%b
)
call :DateToJDN %todayDate% todayJDN=
for /F "tokens=1-3 delims=_." %%a in ('dir /B /A-D *.*') do (
call :DateToJDN %%b fileJDN=
set /A daysOld=todayJDN - fileJDN
if !daysOld! gtr %1 (
echo File "%%a_%%b.%%c" is !daysOld! days old
)
)
goto :EOF
:DateToJDN yyyymmdd jdn=
set yyyymmdd=%1
set /A yyyy=%yyyymmdd:~0,4%, mm=1%yyyymmdd:~4,2% %% 100, dd=1%yyyymmdd:~6% %% 100
set /A a=(mm-14)/12, %2=(1461*(yyyy+4800+a))/4+(367*(mm-2-12*a))/12-(3*((yyyy+4900+a)/100))/4+dd-32075
exit /B
Test this program and change the echo File "%%a_%%b.%%c" ...
command by the desired del "%%a_%%b.%%c"
one.
Reference: http://www.hermetic.ch/cal_stud/jdn.htm#comp
Upvotes: 6