2017-10-17 42 views
0

我想把他們的所有日誌文件/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

是否要將一個文件放在另一個文件之後,或將它們合併到一個文件中,其中所有文件的日誌消息都按照時間戳進行交織和排序? 'cat'命令顯然不起作用。也許你應該改變這個問題作爲評論,否則你會讓某人指出它的語法錯誤。 – simbabque

+2

我沒有看到連接文件的重點,它只是丟失了信息。爲什麼不把它們全部作爲單獨的文件壓縮到一個zip文件中? – Borodin

+0

'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

回答

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"; 
} 
相關問題