Categorized | News

Tags |

Unix: How to delete all files modified in the last x days

Posted on 26 September 2002 by Demian Turner

To do this at the command line for, say, 30 days, the following will do the trick:

find /path/to/dir -name "*.log" -mtime -30 -exec -rm {} \;
  • where /path/to/dir is just that, the path to the target directory
  • “*.log” will only delete files of a specified extension however you can apply any filter you like
  • the -exec switch is very handy when used in conjunction with ‘find’ – in fact you can feed the output of your search to any other command you like, same idea as pipe ‘|’
  • if this is your first time you may wish to try the less destructive -exec mv -f {} ./tmp \;
  • all statements of this type must terminate with ‘\;’ this closes the statement and escapes the final semi-colon
Bookmark and Share

2 Comments For This Post

  1. demian Says:

    for the faint of heart you can require a confirmation before each delete:

    find . -name “*.old” -ok rm {} \;

  2. Demian Turner Says:

    Also very handy for when the /tmp directory is not automatically cleaning PHP session files older than 30 days:

    find /tmp/ -name “sess_*” -mtime +30 -exec mv -f {} /root/tmp \;

    I moved them outside the /tmp dir so they didn’t get found twice, and to verify date before deletion.

Leave a Reply

Categories

Books

Demian Turner's currently-reading book recommendations, reviews, favorite quotes, book clubs, book trivia, book lists

Facebook