0

I want to delete files older than 30 days in a directory, but not in directories below the one I am in.

  • 1
    What do you mean by below? Are you talking about subdirectories or directories listed below when you list in a sorted-by-time order? – perennial_noob May 31 at 23:11
  • I saw the "not delete" in the title after answering your question. Is it correct that you want to delete files in the current directory, but not in subdirectories? – Freddy May 31 at 23:31
2

To list the files before you delete them:

find . -maxdepth 1 -mtime +30 -type f -ls

To delete the files:

find . -maxdepth 1 -mtime +30 -type f -exec rm {} +

with

  • . specifying the current directory
  • -maxdepth 1 descend at most 1 level of directories
  • -mtime +30 only files last modified > 30 days
  • -type f only regular files
  • Should it be +29 ? I think +0 is 1 day ago ? – dedowsdi Jun 1 at 0:07
  • @dedowsdi Yes, you are right, but the question says "older than 30 days", so +30 is correct, i.e. it's 31 days ago and more. – Sparhawk Jun 1 at 0:48
  • In the find man page for option -atime it says "-atime +1, a file has to have been accessed at least two days ago", so -mtime +30 means at least 31 days. I guess it depends on the interpretation of "older than x days". – Freddy Jun 1 at 0:51
0

The zsh shell has special wildcard expansion features that would help.

  • list files older than 30 days in the current directory: ls -d -- *(.m+30)

  • remove files older than 30 days in the current directory: rm -- *(.m+30)

The zsh syntax of *(.m+30) is a wildcard that means:

  • * -- any filename
  • ( ... ) -- with a qualifier of...
  • . -- a regular file (not a directory, etc)
  • m+30 -- the modification time is greater than 30 days ago

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.