【问题标题】:Regex with Sed "clean" a XML line带有 Sed 的正则表达式“清理”一个 XML 行
【发布时间】:2017-02-12 19:04:04
【问题描述】:

我需要从一行中删除所有字符,并且只花一个小时在里面。线条是这样的:

<msg timestamp="20161004 16:24:56.638" level="INFO">Set BAT with value 1</msg>

我需要这个结果:

16:24:56.638

我试过了:

cat output.xml | grep -E "Set BAT with value 1" | sed 's/^<msg timestamp
=\"[0-9]+\s([0-9]+):?\.?\".+/{1}/g'

但现在我似乎不可能得到正确的结果。任何人?

谢谢!!

【问题讨论】:

  • 最好不要使用grepsed 来解析XML。

标签: regex xml sed


【解决方案1】:

使用greppcre,假设&lt;msg&gt; 标签在同一行很好地排列

$ grep -oP '(\d+:){2}[\d.]+(?=.*Set BAT with value 1)' output.xml 
16:24:56.638
  • (\d+:){2}[\d.]+ 要提取的模式
  • (?=.*Set BAT with value 1) 正向前瞻以查看行是否包含 Set BAT with value 1


sed

$ sed -nE '/Set BAT with value 1/ s/.* (([0-9]+:){2}[0-9.]+).*/\1/p' output.xml 
16:24:56.638

此解决方案优于 grep,因为它允许进行就地编辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    • 2020-05-21
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多