Search code examples
bashshellunixunix-timestamp

How to delete specific files in unix


We have a few files on our server instance under /wslogs/instance_name directory and these are all log files created on daily basis.

I am looking for a script to automatically delete those files based on date. So lets say delete files older than 10 days. The problem is that the filename is not purely of date format rather it is

hostname_%m%d%Y_access.log and hostname_%m%d%Y_error.log

For example, ra70960708_12042016_access.log and ra70960708_12042016_error.log (where ra70960708 is the server name or hostname).

I'm trying to use rm command, but unable to figure out how to specify the files here if say I have to delete those which are 10 days older from current date.

Any help would be greatly appreciated.

Cheers,

Ashley


Solution

  • Forgot about name, and use modification time instead:

    The below will list files in current directory, that matches the glob: hostname_*_error.log and which are last modified +10 days ago:

    find . -maxdepth 1 -mindepth 1 \
      -type f -name 'hostname_*_error.log' \
      -mtime +10
    

    They can then be deleted with -delete.

    . is the directory to search in.