如何使用 sed 将纳秒截断为毫秒

How to truncate nanoseconds to milliseconds with sed

我有一个包含格式为 2011-01-01 12:30:10.123456+00 的时间戳的 csv 文件,我想删除纳秒的最后 3 位数字,以获得 2011-01-01 12:30:10.123+00 .

如何使用 sed 或类似工具完成此操作?

需要注意的是,有时精度会发生变化。我只想保留句点后纳秒的前三位数字。

谢谢!

你可以这样做:

var="2011-01-01 12:30:10.123456+00"
echo $var | sed "s/\.*[0-9][0-9][0-9]+/+/g"

gnu sed 将保留第 3 个数字并删除所有其他数字:

cat file
2011-01-01 12:30:10.123456+00
2011-01-01 12:30:10.12+00
2011-01-01 12:30:10.1+00
2011-01-01 12:30:10.12345678+00

sed -r "s/(\.[0-9]{3})[0-9]*//g" file
2011-01-01 12:30:10.123+00
2011-01-01 12:30:10.12+00
2011-01-01 12:30:10.1+00
2011-01-01 12:30:10.123+00

和平主义者的较短版本post:

sed "s/\.*[0-9][0-9][0-9]+/+/g" file #original
sed "s/[0-9]\{3\}+/+/g" file         #Shorter version

2011-01-01 12:30:10.123+00
2011-01-01 12:30:10.12+00
2011-01-01 12:30:10.1+00
2011-01-01 12:30:10.12345+00  #Both version gives more than 3 digits if its more than 6 total