简体   繁体   中英

Perl one liner to find the line having greater date time stamp of two lines.

Need perl one liner to find the line having greater date time stamp of two lines.
The below two sample lines in csv format contains first field as date time stamp:

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

I have the below perl code to identify the date time stamp that is greater of the two, but need a compressed one liner.

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";
}

You don't need to use Time::Piece for this. Date/times in your format are easily sortable, so you can just compare them as strings.

#!/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

Perl oneliner embedded in shell script for tests:

#!/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

Standard version of the above 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);
}

Short version for dates in exactly the same format in the same time zone without Daylight Saving Time and year from 1000 to 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM