将日志文件中的时间戳转换为纪元

我正在访问一个日志文件,每个日志开头都有时间戳。因此,我要提取时间并将其存储在变量中,以便稍后将其转换为纪元时间。

所以我面临的问题是,无论何时执行它,它都会显示date: invalid date并在其旁边打印带有\n的时间戳。例如10/23/19 15:45:01\n10/23/19 15:45:11。同样,在我打印正常时间戳记之间会出现此输出(每次我在评论日期函数时此问题都会停止)

我尝试这样做:

error_time=$(
    cat file | 
    grep -i 'word' -A 5 | 
    grep -o '[0-9][0-9]/[0-9][0-9]/[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]'
)
epoch_time=$(
    date -d '$error_time' +%s
) or $(
    date --date'$error_time' +%s(also +'%s')
)

for error_dir in $(ls -d $path)
do
    for error_logs in $(ls $error_dir)
    do
        error_time=$(
            cat $error_dir/$error_logs | 
            grep -i 'word' -A 5 | 
            grep -o '[0-9][0-9]/[0-9][0-9]/[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]'
        )
        epoch_time=$(
            date -d '$error_time' +%s
        ) or $(
            date --date'$error_time' +%s(also +'%s')
        )
    print $epoch_time
    done
done

预期的输出应该在纪元时间(据我所知秒),我得到的是这样的 \n09/26/19 14:13:37\n09/26/19 14:34:31\n09/26/19 15:22:01

za80967190 回答:将日志文件中的时间戳转换为纪元

perl确实非常适合此类问题:

#!/usr/bin/env perl

# Replace occurrences of 'mm/dd/yy HH:MM:SS' with epoch time

use strict;
use warnings;
use Time::Piece;

while(<>) {
        s@(\d{1,2}/\d{1,2}/\d\d \d{1,2}:\d\d:\d\d)@
                sprintf scalar Time::Piece->strptime(
                $1,"%m/%d/%y %H:%M:%S")->epoch@ge;
        print;
}

结果如下:

$ printf '1/3/19 4:23:04 text \ntext: 12/14/19 12:35:23\n' | ./a.pl
1546489384 text 
text: 1576326923
,

修复后的脚本如下所示:

# don't parse ls
for f in "$path"/*/*; do
    #    ^     ^ quote your variables
    error_time=$(
        # don't try to win useless cat award
        grep -i 'word' -A 5 "$f" | 
        #                   ^  ^ quote your variables
        grep -o '[0-9][0-9]/[0-9][0-9]/[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]'
    )
    epoch_time=$(date -d"$error_time" +%s)
    #                   ^           ^ note
    printf "%d\n" "$epoch_time"
    #             ^           ^ quote your variables
    #    ^ there is no "print" command     
done

了解以下信息可能是明智的选择:

本文链接:https://www.f2er.com/3164137.html

大家都在问