从日志文件转换时间戳
Convert TimeStamp from LogFile
我的日志文件:
created_at,entry_id,field1
2017-09-08 13:21:12 UTC,69,39.00
2017-09-08 14:20:03 UTC,70,42.00
2017-09-08 15:18:32 UTC,71,43.00
2017-09-08 16:16:59 UTC,72,44.00
2017-09-08 17:15:53 UTC,73,44.00
我想重写日志文件,将时间戳从 UTC 转换为 GMT +2,并将 ,
替换为 Tabs
。
转换时间戳并将 c
替换为 bash 的最佳方法是什么?
可能的实现:
#!/bin/bash
while IFS=, read c1 c2 c3; do
if [[ $c1 == "created_at" ]]; then echo -e "$c1\t$c2\t$c3"; continue; fi
TZ=UTC date -d "$c1 +2hours" +"%Y-%m-%d %T"$'\t'"$c2"$'\t'"$c3"
done < file
输出:
created_at entry_id field1
2017-09-08 15:21:12 69 39.00
2017-09-08 16:20:03 70 42.00
2017-09-08 17:18:32 71 43.00
2017-09-08 18:16:59 72 44.00
2017-09-08 19:15:53 73 44.00
缺点:慢
快速而肮脏:
perl -MTime::Piece -F, -ane '
if ($. > 1) {
$t = Time::Piece->strptime($F[0], "%Y-%m-%d %T UTC");
$F[0] = ($t + 7200)->strftime("%Y-%m-%d %T+02:00");
}
print join "\t", @F
' file
如果我想更稳健地做到这一点,并使用 Olson 时区来处理夏令时,我会使用非核心模块并执行:
perl -MDateTime::Format::Strptime -F, -sane '
BEGIN {
$fmt = "%F %T %Z";
$p = DateTime::Format::Strptime->new(pattern => $fmt, time_zone => "UTC");
}
if ($. > 1) {
$t = $p->parse_datetime($F[0]);
$F[0] = $t->set_time_zone($dest_tz)->strftime($fmt);
}
print join "\t", @F
' -- -dest_tz="Europe/Paris" file
created_at entry_id field1
2017-09-08 15:21:12 CEST 69 39.00
2017-09-08 16:20:03 CEST 70 42.00
2017-09-08 17:18:32 CEST 71 43.00
2017-09-08 18:16:59 CEST 72 44.00
2017-09-08 19:15:53 CEST 73 44.00
调整您的目的地时区以适应。
我的日志文件:
created_at,entry_id,field1
2017-09-08 13:21:12 UTC,69,39.00
2017-09-08 14:20:03 UTC,70,42.00
2017-09-08 15:18:32 UTC,71,43.00
2017-09-08 16:16:59 UTC,72,44.00
2017-09-08 17:15:53 UTC,73,44.00
我想重写日志文件,将时间戳从 UTC 转换为 GMT +2,并将 ,
替换为 Tabs
。
转换时间戳并将 c
替换为 bash 的最佳方法是什么?
可能的实现:
#!/bin/bash
while IFS=, read c1 c2 c3; do
if [[ $c1 == "created_at" ]]; then echo -e "$c1\t$c2\t$c3"; continue; fi
TZ=UTC date -d "$c1 +2hours" +"%Y-%m-%d %T"$'\t'"$c2"$'\t'"$c3"
done < file
输出:
created_at entry_id field1 2017-09-08 15:21:12 69 39.00 2017-09-08 16:20:03 70 42.00 2017-09-08 17:18:32 71 43.00 2017-09-08 18:16:59 72 44.00 2017-09-08 19:15:53 73 44.00
缺点:慢
快速而肮脏:
perl -MTime::Piece -F, -ane '
if ($. > 1) {
$t = Time::Piece->strptime($F[0], "%Y-%m-%d %T UTC");
$F[0] = ($t + 7200)->strftime("%Y-%m-%d %T+02:00");
}
print join "\t", @F
' file
如果我想更稳健地做到这一点,并使用 Olson 时区来处理夏令时,我会使用非核心模块并执行:
perl -MDateTime::Format::Strptime -F, -sane '
BEGIN {
$fmt = "%F %T %Z";
$p = DateTime::Format::Strptime->new(pattern => $fmt, time_zone => "UTC");
}
if ($. > 1) {
$t = $p->parse_datetime($F[0]);
$F[0] = $t->set_time_zone($dest_tz)->strftime($fmt);
}
print join "\t", @F
' -- -dest_tz="Europe/Paris" file
created_at entry_id field1
2017-09-08 15:21:12 CEST 69 39.00
2017-09-08 16:20:03 CEST 70 42.00
2017-09-08 17:18:32 CEST 71 43.00
2017-09-08 18:16:59 CEST 72 44.00
2017-09-08 19:15:53 CEST 73 44.00
调整您的目的地时区以适应。