http://www.perlmonks.org?node_id=928166


in reply to Deleting old files from directory

If you are using unix/linux, then an alternative way to find and delete old files is with find and xargs:

find <directory> -type f -ctime +10 -name "*some*pattern*.txt" | xargs rm -f

I have fragments like that in the crontab for the systems I maintain, as it is very easy to setup and then just leave to run for ever.

Replies are listed 'Best First'.
Re^2: Deleting old files from directory
by reisinge (Hermit) on Sep 27, 2011 at 20:37 UTC
    To handle spaces in filenames:
    find <directory> -type f -mtime +10 -name "*some*pattern*.txt" -exec r +m -f '{}' \;
    On first run(s), you should consider using ls -l instead of rm -f.

    I see you've used -ctime; here are the differences among Unix timestamps:

    • Access Time (atime) - time that the file was last accessed (e.g. read) or written to.
    • Modify Time (mtime) - time the actual contents of the file were last modified.
    • Change Time (ctime) - the time that the inode information (permissions, name, etc., i.e. the metadata) was last modified.

    Update: atime info corrected; for more see man 2 stat.

    Have a nice day, j

      I use an explicit pipe to xargs instead of using the built in delete action, because that way it is easier to check I am deleting the correct files, as I can use ls on the end of the xargs command instead of rm.

      Another way to handle spaces in filenames is to configure find to separate output with nulls instead of spaces, and then have xargs expect those nulls.

      find <directory> <conditions> -print0 | xargs -0 ls -l
Re^2: Deleting old files from directory
by i5513 (Pilgrim) on Sep 27, 2011 at 20:21 UTC

    or better using -delete from find actions (in this case -maxdepth is needed too)

    why ctime and not mtime ?

    In the other side, maybe using Find, could be more efficient? I don't know

    Regards,
Re^2: Deleting old files from directory
by Anonymous Monk on Sep 27, 2011 at 22:56 UTC
    Notice also that systems like OS/X may require a slightly different syntax, as may Unix shells other than 'bash.'