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



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

所以我面临的问题是,每当我执行它时,它都会说date: invalid date,并在旁边打印带有n的时间戳。例如,10/23/19 15:45:01n10/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

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

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}/dd d{1,2}:dd:dd)@
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:23n' | ./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 "%dn" "$epoch_time"
#             ^           ^ quote your variables
#    ^ there is no "print" command     
done

了解可能是明智的

  • 关于shell检查,它自动检查脚本并突出显示问题
  • 如何调试bash脚本
  • bash中的单引号和双引号有什么区别
  • 为什么不应该在unix.stackexchange上解析ls和类似线程
  • 并且cat用于连接多个文件,所以不要在单个文件上使用它。执行重定向grep ... < "$file"或将文件作为参数传递给实用程序grep ... "$file"

最新更新