Perl one liner以找到具有更多日期时间戳两行的行。

问题描述 投票:-2回答:2

需要perl one liner来找到具有更多日期时间戳两行的行。 csv格式的以下两个样本行包含第一个字段作为日期时间戳:

2018-02-15 06:10:55-05;2BBB519037;2.1.575017;YY990;Company1;0;0;0;0;0;0;0;0;0;1;1;0;0;4498
2018-02-15 15:40:12-05;2BBB1519037;2.1.575017;YY990;Company1;0;0;0;0;0;0;0;0;0;1;1;0;0;5401

我有以下perl代码来识别两者中较大的日期时间戳,但需要压缩的一个衬里。

use Time::Piece;
my $dateformat = "%Y-%m-%d %H:%M:%S";

my $date1 = "2018-02-15 06:10:55";
my $date2 = "2018-02-15 15:40:12";
my $diff = $date2 - $date1;

$date1 = Time::Piece->strptime($date1, $dateformat);
$date2 = Time::Piece->strptime($date2, $dateformat);

if ($date2 > $date1) {
    print "$date2 is greater";
} else {
    print "$date1 is greater";
}
perl
2个回答
2
投票

你不需要使用Time :: Piece。格式中的日期/时间很容易排序,因此您可以将它们作为字符串进行比较。

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

chomp(my @lines = <DATA>);

if ($lines[0] gt $lines[1]) {
  say "First line has the later timestamp";
} elsif ($lines[0] lt $lines[1]) {
  say "Second line has the later timestamp";
} else {
  say "Timestamps are the same";
}

__DATA__
2018-02-15 06:10:55-05;2BBB519037;2.1.575017;YY990;Company1;0;0;0;0;0;0;0;0;0;1;1;0;0;4498
2018-02-15 15:40:12-05;2BBB1519037;2.1.575017;YY990;Company1;0;0;0;0;0;0;0;0;0;1;1;0;0;5401

0
投票

在shell脚本中嵌入Perl one liner进行测试:

#!/bin/sh
perl -MDate::Parse -ne '$h{$t}=$_ if /^(.*?);/ and $t=str2time($1);END{print $h{shift @K} if @K=sort{$a<=>$b}keys %h}' <<END
2018-02-15 06:10:55-05;2BBB519037;2.1.575017;YY990;Company1;0;0;0;0;0;0;0;0;0;1;1;0;0;4498
2018-02-15 15:40:12-05;2BBB1519037;2.1.575017;YY990;Company1;0;0;0;0;0;0;0;0;0;1;1;0;0;5401
END

以上perl one-liner的标准版本:

use strict;
use warnings;
use Date::Parse;

my %h; # has mapping unix-time number to full line content
LINE: while (defined($_ = readline ARGV)) {
    my $t; # unix-time number extracted from the line
    $h{$t} = $_ if /^(.*?);/ and $t = str2time($1);
}
END {
    my @K; # keys of %h - unix-time found in the file  
    print $h{shift @K} if @K = (sort {$a <=> $b} keys %h);
}

在没有Daylight Saving Time且年份从1000到9999的相同时区中完全相同格式的日期的简短版本。

#!/bin/sh
perl '$h{$t}=$_ if /^(.*?);/;END{print $h{shift @K} if @K=sort keys %h}' <<END
2018-02-15 06:10:55-05;2BBB519037;2.1.575017;YY990;Company1;0;0;0;0;0;0;0;0;0;1;1;0;0;4498
2018-02-15 15:40:12-05;2BBB1519037;2.1.575017;YY990;Company1;0;0;0;0;0;0;0;0;0;1;1;0;0;5401
END
© www.soinside.com 2019 - 2024. All rights reserved.