如何将一定数量的文件放在一个'主'文件中
问题描述:
我想把他们的所有日志文件/var/log
和cat
都转换成主日志文件,然后压缩该主文件。我究竟该怎么做?如何将一定数量的文件放在一个'主'文件中
我在我的代码中有cat
,因为这是我知道如何在bash中完成的。我将如何在Perl中做到这一点?
#!/usr/bin/perl
use strict;
use warnings;
use IO::Compress::Zip qw(zip $ZipError);
# cat /var/log/*log > /home/glork/masterlog.log
my @files = </var/log/*.log>;
zip \@files => 'glork.zip'
or die "zip failed: $ZipError\n";
@files = </var/log/*.log>;
if (@files) {
unlink @files or warn "Problem unlinking @files: $!";
print "The job is done\n";
} else {
warn "No files to unlink!\n";
}
答
正如在评论中指出的那样,有几种较少涉及的方式来做到这一点。如果你真的需要推出自己的产品,Archive::Zip将做任何你告诉它。
#!/usr/bin/env perl
use strict;
use Archive::Zip ':ERROR_CODES';
use File::Temp;
use Carp;
# don't remove "temp" files when filehandle is closed
$File::Temp::KEEP_ALL = 1;
# make a temp directory if not already present
my $dir = './tmp';
if (not -d $dir) {
croak "failed to create directory [$dir]: $!" if not mkdir($dir);
}
my $zip = Archive::Zip->new();
# generate some fake log files to zip up
for my $idx (1 .. 10) {
my $tmp = File::Temp->new(DIR => $dir, SUFFIX => '.log');
my $fn = $tmp->filename();
print $tmp $fn, "\n";
}
# combine the logs into one big one
my $combined = "$dir/combined.log";
open my $out, '>', $combined or die "couldn't write [$combined]: $!";
for my $fn (<$dir/*.log>) {
open my $in, '<', $fn or die "couldn't read [$fn]: $!";
# copy the file line by line so we don't use tons of memory for big files
print($out $_) for <$in>;
}
close $out;
$zip->addFile({ filename => $combined, compressionLevel => 9});
# write out the zip file we made
my $rc = $zip->writeToFileNamed('tmp.zip');
if ($rc != AZ_OK) {
croak "failed to write zip file: $rc";
}
是否要将一个文件放在另一个文件之后,或将它们合并到一个文件中,其中所有文件的日志消息都按照时间戳进行交织和排序? 'cat'命令显然不起作用。也许你应该改变这个问题作为评论,否则你会让某人指出它的语法错误。 – simbabque
我没有看到连接文件的重点,它只是丢失了信息。为什么不把它们全部作为单独的文件压缩到一个zip文件中? – Borodin
'tar cvfz logs.tar.gz/var/log/* log'是我该怎么做的。根本不需要'perl'。如果你真的需要:'tar cvfz logs.tar.gz/var/log/* log && rm -f/var/log/* log'。如果问题是日志整合,那么我也不会这样做,我只是看着更改rsyslog.conf – Sobrique