How can I clean up my logfile directory using Perl or shell scripting?

  • Thread starter Thread starter TomD
  • Start date Start date
T

TomD

Guest
I've got an Ubuntu Linux server that's got logrotate running on it nightly. That's great, but my /var/log directory is looking a bit messy...I've got the log files, and then logfile1.1.gz, logfile1.2.gz, etc, for all my different files. I want to make archive directories that will hold the .gz files (i.e., all mail archived logfiles (mail.1.gz, mail.2.gz, etc) go in in the mail directory; same for all different log files that rotate)

What I want to do is get a perl script in place (a shell script would work too, but I like perl better) that will do the following:

1.) ls -l /var/log
2.) check for lines in that output that have .gz all the way at the end
3.) of the lines that have .gz at the end, strip everything but the beginning of the file name, up to the first "."
4.) Take that word, and check to see if a directory by that name already exists.
4a.) if it does, then take all the log files in /var/log that begin with that name, and end in .gz, and move them into that dir.
4b.) if the dir doesn't exist, then make the dir, and follow 4a.
 
use strict;
use warnings;
use File::Copy;
use File::Path;
opendir LOG, '/var/log' or die;
while (my $sItem = readdir LOG)
{
if ($sItem =~ m/\A(.+?)\..*\.gz\z/)
{
my $sNewDir = $1;
mkpath "/var/log/$sNewDir";
move "/var/log/$sItem", "/var/log/$sNewDir";
} # if
} # while
 
Back
Top