月曜日, 9月 06, 2010

Perl 更新日付が指定日数より前のファイルを圧縮

2008/08/05perlfreak.vox.comより転載)

OSの文字コードがUTF-8のLinux上のSambaサーバで管理しているディレクトリ下のファイルが対象。

===(compress_files.pl ここから)===
#!/usr/bin/perl -w

use File::Find::Rule;
use Encode qw/ from_to /;
#use warnings;
use strict;

# 処理対象ディレクトリパスと日数
my $dir_path = $ARGV[0] if $ARGV[0];
my $days = $ARGV[1] if $ARGV[1];
unless ( $days ) { exit; }

# 指定日数分前のtime
my $days_before = time - 60 * 60 * 24 * $days;

# ログ
my $log_path = '/tmp/compress_files.log';
system( "/usr/bin/touch", $log_path ) unless ( -e $log_path );

# 対象ファイルのパスを取得
my @files = File::Find::Rule->file()
->mtime( "<$days_before" ) ->in( $dir_path );

# 圧縮・削除処理
open OUT, ">> $log_path" or die "Cannot open file: $!\n";
foreach my $file_path ( @files ) {
if ( $file_path =~ /.+\.zip$/ ) { next; }

my $compress_path = $file_path . '.zip';

if ( $file_path =~ /^(.+)\/(.+?)$/ ) {
print $file_path . "\n";
print OUT $file_path . "\n";
my $dir_path = $1;
my $file_name = $2;
my $cp_file_name = $file_name;
from_to( $cp_file_name, 'utf8', 'cp932' );
my $compress_name = $file_name . '.zip';
chdir $dir_path;
system( "/bin/cp", "-p", $file_name, $cp_file_name );
my( $owner, $group, $date, $time ) = (split( / /, `/bin/ls -l $file_name`))[2,3,5,6];
my( $year, $mon, $day ) = split( /-/, $date );
my( $hour, $min ) = split( /:/, $time );
system( "/usr/bin/zip", $compress_name, $cp_file_name );
system( "/bin/chown", "$owner:$group", $compress_name );
system( "/usr/bin/touch", "-m", "-t", "$year$mon$day$hour$min", $compress_name );
system( "/bin/rm", $file_name, $cp_file_name );
}
}
close OUT;

exit;
===(compress_files.pl ここまで)===

0 件のコメント: