【问题标题】:Perl - sort the log files from a directory, pick up the latest generated log file and print only specific dataPerl - 从目录中对日志文件进行排序,选择最新生成的日志文件并仅打印特定数据
【发布时间】:2012-08-21 07:19:50
【问题描述】:

我是 perl 新手,我需要开发一个脚本来对目录中的日志进行排序,获取最新文件并仅从日志文件中复制特定内容并将其打印到新文件中。我写了一个下面的 perl 脚本,我需要你的宝贵意见。

my($dir) = "C:\Luntbuild_Logs\LACOPBOC LACOPBOC_LASQABOCFC_";
$file = #Here i want to pick up the last generated log file from the above dir
my($newLog) = "new.log";
while (<MYFILE>) {
    print "$line" if $line =~ /> @/;
    print "$line" if $line =~ /ORA-/;
 }
 close (MYFILE);

I want my code to pick up the last generated log file from the dir and print the specific lines and redirect the output to the new log file.

现在我的 srript 能够排序和打印最新文件(目录中的所有文件都是 txt 文件),但我无法执行操作

use File::stat;
$dirname = 'C:/Luntbuild_Logs';
$timediff=0;
opendir DIR, "$dirname";
while (defined ($file = readdir(DIR)))
{
                if($file ne "." && $file ne "..")
                {
                                $diff = time()-stat("$dirname/$file")->mtime;
                                if($timediff == 0)
                       {
                                $timediff=$diff;
                                $newest=$file;
                       }
                if($diff<$timediff)
                                       {
                                $timediff=$diff;
                                $newest=$file;
                       }
        }
}
open(FILE,"<$newest");
my(@fprint) = <FILE>;
close FILE;
open(FOUT,">list1.txt") || die("Cannot Open File");
foreach $line (@fprint) {
    print "$line" if $line =~ /> @/;
    print "$line" if $line =~ /ORA-/;
    print FOUT $line;
}
close FOUT;

【问题讨论】:

标签: perl


【解决方案1】:

这是获取目录中文件的简单方法(注意正斜杠在 Windows 中有效,并且是首选):

chdir "C:/Luntbuild_Logs/LACOPBOC LACOPBOC_LASQABOCFC_";
my @files = <*>;

您可能应该确认您只获得了正确类型的文件。在 Windows 上,您通常可以通过扩展来执行此操作。假设所有文件都以 .log 结尾。将上面的最后一行替换为:

my @files = grep {/\.log$/} <*>;

下一步,我建议你看一下this question,它提供了许多用于查找文件修改时间的解决方案。

【讨论】:

    猜你喜欢
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    相关资源
    最近更新 更多