17

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?

33

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
  • 7
    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 '14 at 16:03
  • 1
    @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?) – Eliah Kagan Oct 9 '14 at 0:58
  • 1
    @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 '14 at 13:25
  • 2
    @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.) – Eliah Kagan Oct 9 '14 at 15:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy