Blog

[perl] epoch 秒っぽいやつを置換する

https://metacpan.org/pod/from_unixtime をみてやってみた。

> cat sql_result
id    1
created_at    1419702037
updated_at    1419702037
> perl -MTime::Piece -pe 's/\b(1[0-9]{9})\b/"$1(".localtime($1)->strftime("%F %T").")"/ge' < sql_result
id    1
created_at    1419702037(2014-12-28 02:40:37)
updated_at    1419702037(2014-12-28 02:40:37)

自分の場合だとこんぐらいのワンライナーでいいかな、と。

上記の正規表現は極めて雑だが、以下のように、一般的に求めたい範囲の unix time にはそれなりにマッチする。

> epoch 1000000000
2001-09-09 10:46:40+0900 1000000000
> epoch 1999999999
2033-05-18 12:33:19+0900 1999999999

ちなみにここで利用している epoch コマンドは、僕が日常的に使っているスクリプト。 内容は以下のものであって、極めて便利。

#!/usr/bin/env perl
use strict;
use warnings;
use Time::Piece;
use Pod::Usage;

&main; exit;

sub show($) {
    my $time = shift;
    printf "%s %s\n", $time->strftime("%Y-%m-%d %H:%M:%S%z"), $time->epoch;
}

sub main {
    my $stuff = shift @ARGV;
    if (!defined $stuff) {
        show(localtime());
    } elsif ($stuff =~ /^\d{4}-\d\d$/) {
        my $first = localtime()->strptime($stuff, '%Y-%m');
        my $last = localtime()->strptime($stuff . '-' . $first->month_last_day . ' 23:59:59', '%Y-%m-%d %H:%M:%S');
        show($first);
        show($last);
    } elsif ($stuff =~ /^\d{4}-\d\d-\d\d$/) {
        show(localtime()->strptime($stuff . ' 00:00:00', '%Y-%m-%d %H:%M:%S'));
        show(localtime()->strptime($stuff . ' 23:59:59', '%Y-%m-%d %H:%M:%S'));
    } elsif ($stuff =~ /^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d$/) {
        show(localtime()->strptime($stuff, '%Y-%m-%d %H:%M:%S'));
    } elsif ($stuff =~ /^\d+$/) {
        show(localtime($stuff));
    } else {
        pod2usage(1);
    }
}


__END__

=head1 SYNOPSIS

    $ epoch
    2015-01-04 12:34:49+0900 1420342489

    $ epoch 2013-05
    2013-05-01 00:00:00+0900 1367334000
    2013-05-31 23:59:59+0900 1370012399

    $ epoch 2013-05-02
    2013-05-02 00:00:00+0900 1367420400
    2013-05-02 23:59:59+0900 1367506799

    $ epoch '2013-05-02 04:02:03'
    2013-05-02 04:02:03+0900 1367434923

    $ epoch 1420342489
    2015-01-04 12:34:49+0900 1420342489