I am currently creating a script that deletes files that are more than 7 days. This is my current script.

find -type f -mtime +6 -exec rm -rf {} \;

I need to include a name pattern, so it deletes only those with LOGS in the filename. Sample files:

  • AppA.txt
  • AppB.txt
  • AppA_LOGS.txt
  • AppB_LOGS.txt

It will only delete the AppA_LOGS.txt and AppB_LOGS.txt files (assuming they are older 7 days) and App.txt and AppB.txt will remain even they are more than 7 days old.

How can I add it in my current script? Thank you.

  • find -name "*LOGS*" -type f -mtime +6 -exec rm -rf {} \;
    – FedKad
    Oct 30, 2020 at 8:25

1 Answer 1


To filter by name use the -name predicate which takes a wildcard pattern similar to those used in shell globbing:

find . -name '*_LOGS.txt' -type f -mtime +6 -exec rm -f {} +

It's better to put that filter first, as it's generally less expensive than the ones that are based on file metadata (though some find implementations do that reordering automatically). That way, if a file is excluded because its name doesn't end in _LOGS.txt, find doesn't need to retrieve its metadata.

Like in shell globs, * matches any sequence of characters. Note that contrary to shell globs, there is no special handling of files whose name starts with . (hidden files), so they will be included as well. Same for files in directories whose name starts with ..

Also note that rm can take more than one filename as argument, so you can use + instead of ; as the -exec delimiter. That also has the advantage of find reporting errors by rm in its exit code.

Also note that portably, you need to give at least one file or directory as argument to find for it to know where to search. Some find implementations default to . (the current working directory) when you don't tell it where to look, but some others don't.

If using zsh, you could also just do:

rm -f -- **/*_LOGS.txt(D.m+6)

Where . is the equivalent of -type f, m+6 of -mtime +6 and D also considers hidden files and files in hidden dirs like find does.

Contrary to some find implementations, it will still manage to remove files whose name contains sequence of bytes not forming valid characters in the locale. It could however fail to execute rm if there is a very large list of files to remove (but see the zargs function or the zsh/files module to make rm builtin to work around that).

  • one question please, in zsh the order of these D.m+6 matter? Oct 30, 2020 at 9:09
  • 1
    @αғsнιη, not for those. It would matter for - (what follows applies after symlink resolution) or ^ (negation) , (or)... In terms of perf, I suppose order could matter if there are qualifiers that use different sources of information for the files (lstat, stat, directory contents (F)...), never really looked into it much. Oct 30, 2020 at 9:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .