Deleting files by age

Is there a command to delete all the files in a directory that haven’t been modified in N days? I need to clean up some old logs.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This will delete all files older than 5 days, you can put a -name '*log' in there too to be more precise and you might want to specify a maxdepth in the find command too.

find /some/dir -type f -mtime +5 -delete

Method 2

With zsh and (.m+n) glob qualifiers: . selects only regular files, m+n selects files modified more than n days ago;
e.g. list the files in the current directory that were modified more than 9 days ago:

print -rl -- *(.m+9)

add D to include dot files:

print -rl -- *(D.m+9)

or if you want to recurse (and list e.g. only files ending with .log):

setopt extendedglob
print -rl -- **/*.log(.m+9)

replace print -rl with rm if you’re happy with the result; though you may have to use zargs if you have many files (to avoid arguments list too long):

autoload zargs
zargs ./**/*(.m+9) -- rm


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x