25

By the time, many files are still on my system and I don't need them anymore, so how to delete all files that are one year old at least?

1 Answer 1

50

You can do it with this command

find /path/to/files* -mtime +365 -exec rm {} \;

Some explain

/path/to/files* is the path to the files.

-mtime is used to specify the number of days old that the file is. +365 will find files older than 365 days which is one year

-exec allows you to pass in a command such as rm.


Edit Thanks to @Oli note --> you can do it by:

find /path/to/files* -mtime +365 -delete
5
  • 11
    You should always quote the {} in -exec (so it reads -exec rm "{}" \;). This makes sure that spaces are handled properly... And you could just use the -delete function instead of -exec.
    – Oli
    Jan 31, 2014 at 16:03
  • 2
    @Oli Huh??? (What you have said cannot be right, considering that the shell turns "{}" into {} before passing it to find in the first place; then find substitutes for it. Quoting {} is suggested in case { and } themselves may sometimes be treated specially by the shell--which has nothing to do with blank spaces. And often {} doesn't have to be quoted. I can't think of any situation, at least when invoking find from a Bourne-style shell, when {}, with nothing inside, appearing by itself as an argument, would have to be quoted. Can you?) Oct 9, 2014 at 0:58
  • 2
    @EliahKagan Yeah, turns out find handles escaping for itself but it's not a bad habit to be in while scripting. It doesn't hurt.
    – Oli
    Oct 9, 2014 at 13:25
  • 3
    @Oli But it doesn't help, even in principle. If find didn't handle escaping, "{}" would still have the same effect as {}--just neither would work, instead of both working. That {} and "{}" behave the same isn't--and cannot be--due to any special feature of find. Confusing what gets expanded by the shell with what gets expanded by some other program is a bad habit. We all make that mistake occasionally, but it's still a mistake--not a best practice. (One might still quote {} to help humans see it's not a pattern for brace expansion, but that's unrelated to word splitting.) Oct 9, 2014 at 15:24
  • can i use find . if i am on the active directory? Nov 10, 2023 at 7:23

You must log in to answer this question.