Delete files older than specific file

I need to delete from a folder all files older than a specific file.
Running bash on CentOS 7.

I have a solution for this, but I think there should be a more elegant way do it:


    stat $1 | grep -Po "Modify: K[0-9- :]*"

pit=$(get_modify_time $reference_file)
for f in /folder/0000* ; do [[ "$pit" > "$(get_modify_time $f)" ]] && rm $f ; done
Asked By: csny


I haven’t tried it, but find should be able to handle the whole operation just fine:

$ find dir/ -type f ! -newer reference -delete

… or…

$ find dir/ -type f ! -newer reference ! -name reference -delete


  • ! -newer reference matches files which have been modified less recently than reference.
  • -delete deletes them.
  • ! -name reference excludes reference, in case it is also located under dir/ and you want to keep it.

This should delete all files older than reference, and located under dir/.

Answered By: John WH Smith

compare file modification times with test, using -nt (newer than) and -ot (older than) operators:

if [ "$file1" -ot "$file2" ]; then
    #do whatever you want;
Answered By: serenesat
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.