Command-Line-Interface

將紀元(秒)格式的日期替換為日誌文件中的正常日期

  • September 25, 2014

我在 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.

怎麼用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.

引用自:https://serverfault.com/questions/631216