ファイルの時間形式の変更

ファイルの時間形式の変更

sarコマンドの出力がありますが、時間がPOSIXではありません。

Linux 2.6.32-431.29.2.el6.x86_64 (test.server.com)  2015-08-01  _x86_64_    (32 CPU)

12:00:01 AM     CPU      %usr     %nice      %sys   %iowait    %steal      %irq     %soft    %guest     %idle
12:10:01 AM     all      0.01      0.00      0.07      0.00      0.00      0.00      0.00      0.00     99.93
12:10:01 AM       0      0.01      0.00      0.02      0.00      0.00      0.00      0.00      0.00     99.97
[…]

私は12:00:01 AMからposix 00:00:01までの時間で始まる行の時間を変える方法を見つけようとしています。

どんなアイデアがありますか?

とても感謝しています!

ベストアンサー1

個人的に私はそうするでしょう:

  • 時間をエポック形式で解析します。
  • 目的の出力形式でエポック時間を印刷します。

たとえば、

#!/usr/bin/env perl

use strict;
use warnings;

use Data::Dumper;
use Time::Piece; 

while ( <DATA> ) {
   my ( $time_str ) = m/^([\d\:]+ [AP]M)/;
   print $time_str, "=>",;
   my $newtime = Time::Piece -> strptime ( $time_str, "%I:%M:%S %p" );
   print $newtime->strftime("%H:%M:%S"),"\n";
}

__DATA__
12:00:01 AM     CPU      %usr     %nice      %sys   %iowait    %steal      %irq     %soft    %guest     %idle
12:10:01 AM     all      0.01      0.00      0.07      0.00      0.00      0.00      0.00      0.00     99.93
12:10:01 AM       0      0.01      0.00      0.02      0.00      0.00      0.00      0.00      0.00     99.97

したがって、スクリプトは次のようになります。

#!/usr/bin/env perl

use strict;
use warnings;

use Time::Piece;

while (<>) {
    if ( my ($time_str) = m/^([\d\:]+ [AP]M)/ ) {
        my $new_time_str = Time::Piece->strptime( $time_str, "%I:%M:%S %p" )
            ->strftime("%H:%M:%S");
        s/$time_str/$new_time_str/;
    }
    print;
}

これは「インライン」として機能します。<>Perlの魔法を使用すると、次のことが可能です。

  • ./myscript.pl some_file
  • some_command | ./myscript.pl

次のように線形化することが可能です。

perl -MTime::Piece -pe 's/^([\d\:]+ [AP]M)/Time::Piece->strptime( $1, q{%I:%M:%S %p} )->strftime(q{%H:%M:%S})/e;'

おすすめ記事