【问题标题】:Use Sed to cut out the seconds from a date使用 Sed 从日期中删除秒数
【发布时间】:2012-12-05 16:04:34
【问题描述】:

我在一个文件中有一个 url 数据列表,如下所示:

    http://site.com/some/site.htm,12/5/2012 3:30:39 PM
    http://site.com/some/site.htm,12/5/2012 9:30:30 AM
    https://site.com/some/site.htm,12/5/2012 13:30:30 PM
    http://site.com/some/site.htm,12/5/2012 10:30:39 AM

我希望它看起来像这样:

    http://site.com/some/site.htm,12/5/2012 3:30 PM
    http://site.com/some/site.htm,12/5/2012 9:30 AM
    https://site.com/some/site.htm,12/5/2012 13:30 PM
    http://site.com/some/site.htm,12/5/2012 10:30 AM

基本上是使用 sed 从行中删除 :XX 秒部分。我也不介意它是否也会在几分钟后删除所有内容。我可以使用 sed 或 cut,因为我使用的是批处理文件脚本。有人可以帮忙吗?

到目前为止,我已经尝试了以下方法:

sed 's/.*:([^,*]*) AM/\1/g' file.txt

【问题讨论】:

  • sed 's/.*:([^,*]*) AM/\1/g' file.txt

标签: linux replace sed


【解决方案1】:

点赞sed -r 's/(.*):[0-9]{2}(.*)/\1\2/':

$ cat file
    http://site.com/some/site.htm,12/5/2012 3:30:39 PM
    http://site.com/some/site.htm,12/5/2012 9:30:30 AM
    https://site.com/some/site.htm,12/5/2012 13:30:30 PM
    http://site.com/some/site.htm,12/5/2012 10:30:39 AM

$ sed -r 's/(.*):[0-9]{2}(.*)/\1\2/' file
    http://site.com/some/site.htm,12/5/2012 3:30 PM
    http://site.com/some/site.htm,12/5/2012 9:30 AM
    https://site.com/some/site.htm,12/5/2012 13:30 PM
    http://site.com/some/site.htm,12/5/2012 10:30 AM

解释:

(.*):     # Capture everything up the last : (greedy)
[0-9]{2}  # Match the two digits 
(.*)      # Capture the rest of the line

\1\2      # Replace with the two captured groups

注意:-r 使用扩展正则表达式,可能是 -E,取决于您的 sed 风格,请检查 man

编辑:

$ sed -r 's/[0-9]{2}:[0-9]{2} /00 /' file
    http://site.com/some/site.htm,12/5/2012 3:00 PM
    http://site.com/some/site.htm,12/5/2012 9:00 AM
    https://site.com/some/site.htm,12/5/2012 13:00 PM
    http://site.com/some/site.htm,12/5/2012 10:00 AM

【讨论】:

  • 太棒了!太感谢了!!你是 SED 之神!哈哈。我需要这个,因为我需要清除重复项,非常有帮助!
  • 我要等2分钟才能接受你的回答,这就是你的反应速度! :-)
  • 只是好奇,很难只显示 9:00 AM 、 10:00 等内容。基本上将分钟更改为 :00 ?
  • 老实说,你对 sed 很了不起……我可以弄清楚很多技术性的东西,但 sed 专家是一类特殊的超级人类……哈哈……我想我需要找到如果你知道一本很好的 sed 书。无论如何,再次感谢..非常感谢..
【解决方案2】:

一个简单的解决方案,只需查找冒号后跟一个空格后的 2 位数字,然后只替换为空格。

sed 's/:[0-9][0-9] / /g' file.txt

【讨论】:

    【解决方案3】:

    一个非常简单的解决方案:

    sed 's/:.. / /' file
    

    但这可能不推荐,因为它太通用了,如果格式发生轻微变化,可能会出错。

    【讨论】:

      【解决方案4】:

      另一种解决方案:

      sed -r 's/...( [AP]M)$/\1/' file.txt
      

      匹配以空格结尾且后跟 AM 或 PM 的行,并删除其前面的任何三个字符。

      $ 匹配行尾,括号保留AMPM,因此您可以在替换文本中使用\1 引用它。 -r 命令行选项允许使用扩展的正则表达式(\1 参考需要)。

      【讨论】:

        猜你喜欢
        • 2015-10-13
        • 2019-02-05
        • 2023-01-31
        • 2014-01-05
        • 2017-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多