Issue
Hello I have a text file with below entries
MySql-DataBase-2020-09-22_120712.zip
MySql-DataBase-2020-09-22_120947.zip
MySql-DataBase-2020-09-23_153159.zip
MySql-DataBase-2020-09-23_153434.zip
MySql-DataBase-2020-09-24_053634.zip
MySql-DataBase-2020-09-24_053910.zip
MySql-DataBase-2020-09-25_053255.zip
MySql-DataBase-2020-09-25_053530.zip
MySql-DataBase-2020-09-26_055307.zip
MySql-DataBase-2020-09-26_055542.zip
MySql-DataBase-2020-09-27_063328.zip
MySql-DataBase-2020-09-27_063603.zi
MySql-DataBase-2020-10-01_210715.zip
MySql-DataBase-2020-10-01_210950.zip
MySql-DataBase-2020-10-02_033726.zip
MySql-DataBase-2020-10-02_034001.zip
MySql-DataBase-2020-10-03_064238.zip
MySql-DataBase-2020-10-03_064513.zip
MySql-DataBase-2020-10-04_043117.zip
MySql-DataBase-2020-10-04_043353.zip
MySql-DataBase-2020-10-05_050735.zip
MySql-DataBase-2020-10-05_051010.zip
MySql-DataBase-2020-10-06_073457.zip
MySql-DataBase-2020-10-06_073733.zip
MySql-DataBase-2020-10-07_033928.zip
MySql-DataBase-2020-10-07_034204.zip
MySql-DataBase-2020-10-08_014822.zip
MySql-DataBase-2020-10-08_015059.zip
MySql-DataBase-2020-10-09_033301.zip
MySql-DataBase-2020-10-09_033537.zip
I want to select only files between [today's date -4days] & [to whichever old date]
I tried to search on something like this but couldn't find anything :(
Can anyone please help me with any grep, awk command or any small php or python script which can do this?
Solution
The interesting thing about your entries that is a really good practice is to have a naming convention, and the best is that you use a YYYY-MM-DD
date format. This format is interesting because you just have compare string values to get which one is newer. For exemple if you have '2020-10-25'
, it's greater than '2020-10-20'
and it's also newer in time. So you can use a simple lexicographic comparison like that :
import datetime
from datetime import timedelta
#the file in which are the entries
filename = 'your_file'
#creating a start date by takin current date and subtracting 4 days
startDate = (datetime.datetime.today() + timedelta(days=-4)).strftime('%Y-%m-%d')
endDate = '2020-10-08' #whatever date you want
startFile = 'MySql-DataBase-' + startDate
endFile = 'MySql-DataBase-' + endDate
#open the file and get all entries
with open(filename) as f:
content = f.readlines()
myFiles = [x.strip() for x in content]
# Adding all the file that name is between startFile and endFile
res = [file for file in myFiles if startFile < file < endFile]
print(res)
Answered By - Amiral ASTERO