13

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:

reference_file=/my/reference/file

get_modify_time()
{
    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
25

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

Basically:

  • ! -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/.

  • 2
    Perfect :). Just added -maxdepth 1 to keep the search not recursive – csny Feb 25 '15 at 12:33
  • 3
    ! -newer means "not newer", so "older or the same age"; the file itself will be matched if it's in the path find looks at, just something to keep in mind. – ferada May 14 '15 at 9:31
  • 1
    @ferada It will not if you exclude it, which is why my answer also includes ! -name reference (see the third bullet). – John WH Smith May 14 '15 at 9:34
5

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

if [ "$file1" -ot "$file2" ]; then
    #do whatever you want;
fi
  • 1
    Thanks, that's better than my solution but you still need to iterate all files in the folder and compare... The other answer is even more elegant – csny Feb 25 '15 at 12:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.