如何将一定数量的文件放在一个“主”文件中

时间:2017-10-17 14:14:25

标签: perl

我想将/var/logcat中的所有日志文件放入主日志文件中,然后压缩该主文件。我到底该怎么做?

我的代码中有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";
 }

1 个答案:

答案 0 :(得分:0)

正如评论中所指出的,有几种不那么简单的方法可以做到这一点。如果你真的需要自己动手,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";
}