Finding and deleting files with a specific date
You can use find
. Calculate date according to your requirement and use,
find /tmp -maxdepth 1 -mtime -1 -type f -name "DBG_A_sql*" -print
After confirming it delete them,
find /tmp -maxdepth 1 -mtime -1 -type f -name "DBG_A_sql*" -delete
For a start, finding files created on a certain time is a bit hard, since the creation time isn't usually saved anywhere or is hard to get at. What you have is mtime
, or the last modification time, and ctime
which is the "change" time, updated on any changes to the inode. I'll assume you want the modification time.
Finding files modified on a given date turned out to be mildly interesting, since find
appears to make it a bit hard to get it right with files created on exactly midnight.
If we know the relative time (i.e. it was yesterday), we could use
find -daystart -mtime 1
, but it finds the file modified on the wrong midnight, Aug 8 00:00
. However, this seems to work:
find dir/ -daystart -mtime +0 \! -mtime +1 -ls
If don't want to calculate the relative time, and your find
has -newerXY
:
find dir/ -newermt 'Aug 7 00:00' \! -newermt 'Aug 8 00:00' -ls
Again, this gets the files created exactly on midnight wrong, because the comparison is "newer", not "newer or as old as". Though if your system has subsecond precision for timestamps, it might be hard to hit that, but happens if you test with files created by touch
...
A hairy workaround to that would be something like this:
find dir/ -newermt 'Aug 6 23:59:59.999999999' \! -newermt 'Aug 7 23:59:59.999999999' -ls
In any case, add the necessary -name "DBG_A_sql*"
to only take the files with the correct name. You can replace the -ls
at the end with -delete
to delete the files instead of listing. (-ls
, -delete
and -newerXY
exist at least in GNU find and the BSD find on OS X.)
Of course you could actually parse the text representation of the date, but ls
makes it hard to get right if some joker creates files with unprintable characters in them. Sure, the example files don't have any such, but in general, anyone could create them, especially in /tmp
.
(Though with | xargs rm
you'd just miss those files, and since file names can't contain slashes, it would be hard for anyone to point your rm
to another directory.)
Just bash loop
for file in /tmp/DBG_A_sql* ; do
[ "$(date -I -r "$file")" == "2016-08-07" ] && rm "$file"
done