将日志文件中的纪元(秒)格式的日期替换为正常格式

将日志文件中的纪元(秒)格式的日期替换为正常格式

我在一台 ubuntu 机器上尝试读取日志文件,发现日志包含纪元格式(秒)的日期和时间。如何从命令行将这些数字日期转换为任何可读格式?

1411622206, HOST ALERT, host-001,DOWN,SOFT,1,CHECK_NRPE, Socket timeout after 10 seconds.
1411622586, HOST ALERT, host-001,DOWN,SOFT,1,CHECK_NRPE, Socket timeout after 10 seconds.
1411623976, HOST ALERT, host-021,DOWN,SOFT,1,CHECK_NRPE, Socket timeout after 10 seconds.
1411624986, HOST ALERT, host-055,DOWN,SOFT,1,CHECK_NRPE, Socket timeout after 10 seconds.
1411625076, HOST ALERT, host-023,DOWN,SOFT,1,CHECK_NRPE, Socket timeout after 10 seconds.
1411625356, HOST ALERT, host-032,DOWN,SOFT,1,CHECK_NRPE, Socket timeout after 10 seconds.
1411625736, HOST ALERT, host-044,DOWN,SOFT,1,CHECK_NRPE, Socket timeout after 10 seconds.

答案1

那么使用呢date -d@SECONDS_SINCE_1970 [some format]

while IFS=, read -r f1 f2
do
    echo "$(date -d@$f1),$f2"
done < file

然后您可以使用日期选项,以便您可以获得例如:

$ date -d@1411622586 "+%D %T"
09/25/14 07:23:06

测试

$ while IFS=, read -r f1 f2; do echo "$(date -d@$f1),$f2"; done < file
Thu Sep 25 07:16:46 CEST 2014, HOST ALERT, host-001,DOWN,SOFT,1,CHECK_NRPE, Socket timeout after 10 seconds.
Thu Sep 25 07:23:06 CEST 2014, HOST ALERT, host-001,DOWN,SOFT,1,CHECK_NRPE, Socket timeout after 10 seconds.
Thu Sep 25 07:46:16 CEST 2014, HOST ALERT, host-021,DOWN,SOFT,1,CHECK_NRPE, Socket timeout after 10 seconds.
Thu Sep 25 08:03:06 CEST 2014, HOST ALERT, host-055,DOWN,SOFT,1,CHECK_NRPE, Socket timeout after 10 seconds.
Thu Sep 25 08:04:36 CEST 2014, HOST ALERT, host-023,DOWN,SOFT,1,CHECK_NRPE, Socket timeout after 10 seconds.
Thu Sep 25 08:09:16 CEST 2014, HOST ALERT, host-032,DOWN,SOFT,1,CHECK_NRPE, Socket timeout after 10 seconds.
Thu Sep 25 08:15:36 CEST 2014, HOST ALERT, host-044,DOWN,SOFT,1,CHECK_NRPE, Socket timeout after 10 seconds.

答案2

摘自date手册(info date):

要将如此难以处理的秒数转换回更易读的形式,请使用如下命令:

# local time zone used
date -d '1970-01-01 UTC 946684800 seconds' +"%Y-%m-%d %T %z"
1999-12-31 19:00:00 -0500

或者,如果您不介意依赖@coreutils 5.3.0 以来的功能,您可以将其缩短为:

date -d @946684800 +"%F %T %z"
1999-12-31 19:00:00 -0500

通常最好输出相对于 UTC 的日期和时间:

date -u -d '1970-01-01 946684800 seconds' +"%Y-%m-%d %T %z"
2000-01-01 00:00:00 +0000

相关内容