【问题标题】:Improve sed modification between two patterns改进两种模式之间的 sed 修改
【发布时间】:2022-10-24 05:11:23
【问题描述】:

我有这个文本文件:

    cat MyFile.xml | grep IndiceKK

      <Ref IndiceKK="22">
      <Ref IndiceKK="22">
...
      <Ref IndiceKK="22">
      <Ref IndiceKK="22">
      <Ref IndiceKK="22.589">
      <Ref IndiceKK="22.42">
      <Ref IndiceKK="22.47">
      <Ref IndiceKK="22">
      <Ref IndiceKK="22">
...
      <Ref IndiceKK="22">
      <Ref IndiceKK="22">
      <Ref IndiceKK="22.47">
      <Ref IndiceKK="22">
      <Ref IndiceKK="22">
      <Ref IndiceKK="22.03">
      <Ref IndiceKK="22">

我想保留所有文本,但只需将“22.xx”替换为“22”:

Expected:
      <Ref IndiceKK="22">
      <Ref IndiceKK="22">
...
      <Ref IndiceKK="22">
      <Ref IndiceKK="22">

使用sed -i -e '/IndiceKK/ s/22.[^ ]*/22/g' MyFile.xml,我可以拥有&lt;Ref IndiceKK="22,但最后我失去了"&gt;。 所以,我保存"&gt; 的诀窍是手动添加这些字符:sed -i -e '/IndiceKK/ s/22.[^ ]*/22\"&gt;/g' MyFile.xml。就我而言,没关系,但不可扩展,例如,如果行中后面还有其他文本......

请问,你有提议吗?先感谢您

【问题讨论】:

  • sed 和正则表达式是使用 xml 的错误工具。可能与 xmlstarlet 无关
  • 请发布有效的 XML。

标签: shell design-patterns sed replace


【解决方案1】:

sed -i -e '/IndiceKK/s/22.[0-9]*/22/' MyFile.xml

  • . 匹配句点,因为. 匹配任何字符
  • 匹配数字[0-9]不是非空格[^ ]
  • 不要使用g 进行全局匹配...不需要

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 2018-12-30
    • 2013-06-03
    • 1970-01-01
    • 2022-07-14
    • 1970-01-01
    • 2020-05-08
    相关资源
    最近更新 更多