How do I delete files greater than a certain date on linux
Occasionally I extract an an archive into the wrong folder and would like to move or delete the newly extracted files.
What is the easiest way to do this via the command line? Can I somehow search for all files that are newer than the extraction time and pipe that into rm?
Thanks
Edit: As noted in the comments, tar
modifies the mtime and ctime of the extracted files to match the dates in the archive, so this first method won't work unless the -m
flag was used during extraction. The last method is optimal, but may result in deleting files you want if filenames collide.
find
supports a -newer
file
flag, specifying it should find files newer than file. touch
has a -t argument to modify the access/modify time on a file. So to fix an oops that occurred around 7:25:30 PM:
$ tar xzf whoops.tar.gz
$ touch -t 200909261925.30 whoops-timestamp
$ find . -newer whoops-timestamp
And if you're confident that displayed the correct files:
$ find . -newer whoops-timestamp -print0 | xargs -0 rm -v
An alternative is to delete all the files listed in the archive you just extracted:
$ tar tfz whoops.tar.gz | xargs rm -v
Another alternative with find:
$ find "/path/to_clean/" -type f -mtime +30 -print0 | xargs -0 rm -f
where the +30 is the number of days you wish to keep.