2

Assume, I have log files with this name format.

NameLog.log.2014-09-27
NameLog.log.2014-09-28
NameLog.log.2014-09-29
NameLog.log.2014-09-30
NameLog.log.2014-10-01
NameLog.log.2014-10-02
NameLog.log.2014-10-03
NameLog.log.2014-10-04

I want to delete the log file only

NameLog.log.2014-09-27
NameLog.log.2014-09-28
NameLog.log.2014-09-29
NameLog.log.2014-09-30

Actually I want the file log keep just 30 files. How to solve this with a bash script?

2
  • 1
    Why are you trying to reinvent the wheel? – Philip Kendall Oct 6 '14 at 9:02
  • I don't how to solve with format file name. But I was think with easy linux commands. – Ory Oct 7 '14 at 7:27
12

The easiest way to accomplish what you want, is to delete all files in the directory that are older than 30 days. You can use this find command:

find /path/to/log/ -maxdepth 1 -name "NameLog.log*" -mtime +30 -delete

Explanation: (see: explainshell)

  • -maxdepth 1: don't go deeper into the folder structure
  • -name "NameLog.log*": applies only on log file with that name
  • -mtime +30: that have a modification time older than 30 days
  • -delete: delete them
3
  • +1 for adressing the root of the problem. And +1 for making me discover explainshell ^^ – Olivier Dulac Oct 6 '14 at 10:54
  • @OlivierDulac so, +2 in total? =) – chaos Oct 6 '14 at 11:02
  • 1
    I wish I could ^^ (and I didn't click twice ;) ) – Olivier Dulac Oct 6 '14 at 11:20

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.