使用Perl批量读取文件最后行

使用Perl批量读取文件最后行

面对成百上千个文件,有时我们需要查看它的最后行,单个文件打开将耗费大量时间,而通过Perl提取出最后行,将快速的帮助我们处理繁琐的事务。

特性


整个目录完全遍历,自动提取最后行

提取出的文件结构


Perl代码


#!/usr/bin/perl
use warnings;

###########################################
#./readlast_line.pl log/
###########################################

my $indir = $ARGV[0];

opendir DIR, $indir or die "Connot open $indir: $!";

unlink "temp_line";
open(OUTFILE, ">>temp_line") || die ("Could not open file temp_line ! \n");

foreach my $file (sort readdir DIR){            #遍历目录下的文件
    if($file =~ /^\./){
        next;
    }
    #print "$indir$file\n";
    print OUTFILE "\t\t    $indir$file  \t\t \n";   #输出文件名及其路径

    my $last_line = `tail -10 $indir$file`;         #反引号捕获
    print OUTFILE "$last_line \n";
    print OUTFILE "\n\n\n";                            #分割不同文件之间的换行
}

close OUTFILE;
rename 'temp_line','filelast_line';

print "\nOutput file: filelast_line\n";
posted @ 2017-06-08 10:50  乔_木  阅读(1939)  评论(0编辑  收藏  举报