如何使用Perl在两个时间戳之间的文件中搜索行?

Mat*_*coe 5 regex perl timestamp

在Perl中,我试图读取一个日志文件,并且只打印具有两个特定时间之间的时间戳的行.时间格式为hh:mm:ss,这始终是每个日志的第三个值.例如,我会搜索在12:52:33到12:59:33之间的行

我是Perl的新手,并且不知道采取哪条路线来开始编程.我很确定这会使用某种类型的正则表达式,但对于我的生活,我甚至无法理解那将是什么.有人可以帮助我这个.

另外,为了使这更加困难,我必须使用核心Perl模块执行此操作,因为我的公司不允许我使用任何其他模块,直到它们经过测试和验证,对脚本可能没有任何系统的不良影响与...相互作用.

Eth*_*her 2

在伪代码中,你会做这样的事情:

  • 逐行读取文件:
    • 解析该行的时间戳。
    • 如果小于开始时间,则跳到下一行。
    • 如果大于结束时间,则跳到下一行!
    • else: 这是你想要的一行:打印出来。

这对于您的需求来说可能太先进了,但是触发器运算符 ..立即浮现在脑海中,因为它在这里很有用。

对于从 stdin 读取文件,这是常规模式:

while (my $line = <>)
{
     # do stuff...
}
Run Code Online (Sandbox Code Playgroud)

split使用(参见perldoc -f split )可以轻松地将行解析为字段。您可能需要用制表符或空格分隔行,具体取决于格式。

获得特定字段(包含时间戳)后,您可以使用自定义正则表达式检查它。阅读perldoc perlre中的内容。

以下内容可能会让您更接近:

use strict;
use warnings;

use POSIX 'mktime';
my $starttime = mktime(33, 52, 12);
my $endtime = mktime(33, 59, 12);

while (my $line = <>)
{
    # split into fields using whitespace as the delimiter
    my @fields = split(/\s+/, $line);

    # the timestamp is the 3rd field
    my $timestamp = $fields[2];

    my ($hour, $min, $sec) = split(':', $timestamp);
    my $time = mktime($sec, $min, $hour);

    next unless ($time < $starttime) .. ($time > $endtime);
    print $line;
}
Run Code Online (Sandbox Code Playgroud)

  • 这样的任务非常适合触发器运算符。 (2认同)