16

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 

2 Answers 2

33

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

3
  • 2
    Perfect :). Just added -maxdepth 1 to keep the search not recursive Commented Feb 25, 2015 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. Commented May 14, 2015 at 9:31
  • 2
    @ferada It will not if you exclude it, which is why my answer also includes ! -name reference (see the third bullet). Commented May 14, 2015 at 9:34
8

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
  • 2
    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 Commented Feb 25, 2015 at 12:36

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.