This should do everything you have requested:
#!/usr/bin/perl
# 1. Get the base file name of all files in the log directory that end in .gz
# 2. Create a sub-directory according to the base name if it doesn't already exist
# 3. Move all files with that base name to that sub-directory.
# -> Assumption: That you don't want to overwrite any existing files in the sub-directory that
# have the same name as the file you are moving. If you do, then set the $no_overwrite variable to 0
# and it will overwrite any files in the sub-directory with the same file name.
use strict;
use warnings;
use File::Basename; # Standard Perl Module
my $debug = 1; # Set to 0 to suppress console messages. Keep as 1 until you are happy the script works.
my $no_overwrite = 1; # Set to 0 if you want to overwrite existing .gz files in the sub-directory if they already exist
my $log_path = '/var/log';
my @log_files = glob "$log_path/*";
# Cycle through each file in the log directory and process them accordingly
foreach my $log_file (@log_files) {
next unless ($log_file =~ /\.gz$/i); # Process only files ending in .gz (regardless of case)
my ($file_name,$directory,$suffix) = fileparse($log_file, qr/\.gz/i);
my $base_file = $file_name;
$base_file =~ s/^(.*?)\..*$/$1/; # Extract the base filename up to the first dot if it has a dot
my $sub_dir = "$directory$base_file";
unless (-e $sub_dir) { # Create the sub-directory if it doesn't already exist
mkdir ($sub_dir) or die "Unable to create sub-directory: $sub_dir ($!)\n";
print "Created sub-directory: $sub_dir\n" if ($debug);
}
my $new_file = "$sub_dir/$file_name$suffix";
# Now move the file to the sub-directory. If you don't want to overwrite existing files in the
# subdirectory (that is, $no_overwrite is a true value) then the file name will need to be
# modified so that it becomes unique.
if ((-e "$new_file") and ($no_overwrite)) {
print "File $new_file already exists in sub-directory, modifying the file name before moving it as we don't want to overwrite the existing file.\n" if ($debug);
my $count = 2;
my $modified_file_name = "$file_name-$count";
my $modified_new_file = "$sub_dir/$modified_file_name$suffix";
until (! -e "$sub_dir/$modified_file_name$suffix") {
$count++; # Keep incrementing until we arrive at a unique file name
$modified_file_name = "$file_name-$count";
$modified_new_file = "$sub_dir/$modified_file_name$suffix";
}
print "Moving $log_file to $modified_new_file\n" if ($debug);
rename ($log_file, $modified_new_file) or die "Unable to move the file $modified_new_file ($!)\n";
}
# Move the file if it file doesn't already exist or if we don't mind overwriting existing files
else {
print "Moving $log_file to $new_file\n" if ($debug);
rename ($log_file, $new_file) or die "Unable to move the file $new_file ($!)\n";
}
}