如何使用sed从时间戳中删除毫秒? [英] How to remove the milliseconds from timestamps with sed?

查看:114
本文介绍了如何使用sed从时间戳中删除毫秒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的输入文件如下:

12/13/2011,07:14:13.724,12/13/2011 07:14:13.724,231.56.3.245,LasVegas,US

我希望得到以下信息:

12/13/2011,07:14:13,12/13/2011 07:14:13,231.56.3.245,LasVegas,US

我尝试了这个,但是没有成功:

I tried this, but with no success:

sed "s/[0-9]{2}\:[0-9]{2}\:[0-9]{2}\(\.[0-9]{1,3}\)/\1/g" input_file.csv > output.csv

推荐答案

sed 's/\(:[0-9][0-9]\)\.[0-9]\{3\}/\1/g' input_file.csv > output.csv

您快到了.在经典的sed中,必须在括号和花括号前使用反斜杠以使其成为元字符.某些版本的sed可能具有反转操作的机制,因此默认情况下,大括号和括号是元字符,但这在跨平台上并不可靠.

You were almost there. In classic sed, you have to use backslashes in front of parentheses and braces to make them into metacharacters. Some versions of sed may have a mechanism to invert operations, so that the braces and parentheses are metacharacters by default, but that's not reliable across platforms.

也(强烈建议):在sed命令周围使用单引号.否则,在sed看到之前,shell会在解释那些反斜杠(以及任何$符号等)时遇到麻烦.通常,这会使编码器(尤其是维护编码器)感到困惑.实际上,只要有可能,就在程序的参数周围使用单引号.不要对此抱有偏执-如果您需要对变量进行插值,请这样做.但是单引号通常更容易编写代码,最终更容易理解.

Also (strong recommendation): use single quotes around the sed command. Otherwise, the shell gets a crack at interpreting those backslashes (and any $ signs, etc) before sed sees it. Usually, this confuses the coder (and especially the maintaining coder). In fact, use single quotes around arguments to programs whenever you can. Don't get paranoid about it - if you need to interpolate a variable, do so. But single-quoting is generally easier to code, and ultimately easier to understand.

我选择只在一个时间单元上工作;您正在研究三个.最终,给定系统形成的输入数据,结果没有差异-但是脚本的可读性差异很小.

I chose to work on just one time unit; you were working on three. Ultimately, given systematically formed input data, there is no difference in the result - but there is a (small) difference in the readability of the script.

这篇关于如何使用sed从时间戳中删除毫秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆