分类 Perl脚本 下的文章

Perl来获取Linux文件的3个时间

利用Perl来获取Linux文件的3个时间


#!/usr/bin/perl

($atime,$mtime,$ctime) = &getFileAMCTime($_); 传进来一个文件名
print "Atime:$atime Mtime:$mtime Ctime:$ctime\n";

#获取文件的atime,mtime,ctime
sub getFileAMCTime {
     $filename = shift @_;
     my ($atime,$mtime ,$ctime) = (stat ($filename))[8,9,10];
     $atime = &getTime($atime);
     $mtime = &getTime($mtime);
     $ctime = &getTime($ctime);

     #将日期时间格式转换为比较友好的格式
     sub getTime {
          my $time = shift @_;
          my($sec,$min,$hour,$day,$mon,$year) = (localtime $time)[0..5];
          $time = sprintf "%4d-%02d-%02d %2d:%02d:%02d",$year + 1900,$mon + 1,$day,$hour,$min,$sec;
          return $time;
     }
     return $atime,$mtime,$ctime;
}

批量重命名文件后缀名脚本

批量重命名文件后缀名小脚本, 比如 .3gp 命名为 .mp3,请自行修改后缀名和正则表达式。


#!/usr/bin/perl
use File::Find;

# 批量重命名文件的后缀名
# 比如 .3gp 命名为 .mp3

my $gp_root = "/data"; 
my $old_suffix = "\.3gp\$";
my $new_suffix = ".mp3";

my @result;

sub process {
    push @result,$File::Find::name if(/$old_suffix/);
}

sub rename_file {
    foreach my $old (@result){
        (my $new = $old) =~ s/$old_suffix/$new_suffix/;
        if (-e $new){
            warn "Can't rename $old to $new: $new exists\n";
        }elsif (rename $old,$new){
            print "$old --> $new ...OK\n";
        }else {
            warn "rename $old to $new failed: $!\n";
        }
    }
}

find(\&process,$gp_root);
&rename_file;

删除过期日志脚本

脚本功能:

删除过期日志文件

内容如下:


#!/usr/bin/perl
use File::Path 'rmtree';

my $expire_day = 20;
my $delete_log = "delete_log.log";
my $date = &getDateTime();
my $pattern = ".+[0-9]{4}\-[0-9]{2}+\-[0-9]{2}.+";  # 修改为自己的正则表达式

my @will_delete_file_root = ("/data/log1","/data/log2");                

open DELETELOG,">>","$delete_log" or warn "Can't open $delete_log: $!";
print DELETELOG "############# $date #################\n";

foreach (@will_delete_file_root){
    &deleteExpireFile($_);
}
print DELETELOG "\n";
close DELETELOG;

sub deleteExpireFile(){
    my $will_delete_filedir = shift @_;
    chdir "$will_delete_filedir" or die "Can't chdir to $will_delete_filedir: $!";
    opendir FILEDIR,"$will_delete_filedir" or die "Can't open $will_delete_filedir: $!";
    foreach (readdir FILEDIR){
        next if ($_ eq '.');
        next if ($_ eq '..');
        if ($_ =~ /$pattern/ and -M $_ > $expire_day) {
            print DELETELOG "$_\n";
            rmtree($_);
        }
    }
    close FILEDIR;
}

sub getDateTime() {
      my ($sec, $min, $hour, $mday, $mon, $year) = (localtime)[0..5];
      $date = sprintf "%4d-%02d-%02d %2d:%02d:%02d" ,$year + 1900,$mon + 1 ,$mday ,$hour ,$min ,$sec;
}