如何通过时区更改 Linux 中分隔文件中字段的时间戳?
How to change timestamps via timezone for a field in a delimited file in Linux?
假设我有如下文件:
1,aaa,2016-12-01 01:02:03 EST,bbb
2,ccc,2016-12-02 04:05:06 CST,ddd
3,eee,2016-12-03 07:08:09 EST,fff
我想添加第 5 个字段,这是字段 3 中的时间戳,但已转换为 UTC。
这可以调用 date
或 Linux 中的任何内容。我不太担心性能,因为它只在少量文件上经常调用一次。
我似乎想不出最好的方法。 awk 的 strftime
没有收到时区字段,所以我想不出最好的使用方法。
使用 Bash 循环:
while IFS=, read -r -a linearr; do
printf '%s,' "${linearr[@]}"
date +'%F %T %Z' -u -d "${linearr[2]}"
done < infile
这导致
1,aaa,2016-12-01 01:02:03 EST,bbb,2016-12-01 06:02:03 UTC
2,ccc,2016-12-02 04:05:06 CST,ddd,2016-12-02 10:05:06 UTC
3,eee,2016-12-03 07:08:09 EST,fff,2016-12-03 12:08:09 UTC
这会将每一行读入数组 linearr
,打印行末尾添加的逗号,然后附加新的日期字符串。
或者,paste
和 cut
:
paste -d, infile <(while read line; do date +'%F %T %Z' -u -d "$line"; done < <(cut -d , -f 3 infile))
或者,更具可读性:
paste -d , \
infile \
<(while read line; do
date +'%F %T %Z' -u -d "$line"
done < <(cut -d, -f3 infile)
)
请注意 date
的 -d
选项特定于 GNU date
。 POSIX date
没有使用当前系统日期以外的日期的选项,FreeBSD 中的 date
使用另一个选项 -r
,它期望 "seconds since the Epoch" 作为它的论点。
假设我有如下文件:
1,aaa,2016-12-01 01:02:03 EST,bbb
2,ccc,2016-12-02 04:05:06 CST,ddd
3,eee,2016-12-03 07:08:09 EST,fff
我想添加第 5 个字段,这是字段 3 中的时间戳,但已转换为 UTC。
这可以调用 date
或 Linux 中的任何内容。我不太担心性能,因为它只在少量文件上经常调用一次。
我似乎想不出最好的方法。 awk 的 strftime
没有收到时区字段,所以我想不出最好的使用方法。
使用 Bash 循环:
while IFS=, read -r -a linearr; do
printf '%s,' "${linearr[@]}"
date +'%F %T %Z' -u -d "${linearr[2]}"
done < infile
这导致
1,aaa,2016-12-01 01:02:03 EST,bbb,2016-12-01 06:02:03 UTC
2,ccc,2016-12-02 04:05:06 CST,ddd,2016-12-02 10:05:06 UTC
3,eee,2016-12-03 07:08:09 EST,fff,2016-12-03 12:08:09 UTC
这会将每一行读入数组 linearr
,打印行末尾添加的逗号,然后附加新的日期字符串。
或者,paste
和 cut
:
paste -d, infile <(while read line; do date +'%F %T %Z' -u -d "$line"; done < <(cut -d , -f 3 infile))
或者,更具可读性:
paste -d , \
infile \
<(while read line; do
date +'%F %T %Z' -u -d "$line"
done < <(cut -d, -f3 infile)
)
请注意 date
的 -d
选项特定于 GNU date
。 POSIX date
没有使用当前系统日期以外的日期的选项,FreeBSD 中的 date
使用另一个选项 -r
,它期望 "seconds since the Epoch" 作为它的论点。