【问题标题】:Regex Pattern Replace正则表达式模式替换
【发布时间】:2016-10-20 20:51:37
【问题描述】:

所以我想替换以下内容

<duration>89</duration>

与 (预期的结果或者至少应该变成这样:)

\n<duration>89</duration>

所以基本上用正则表达式中的 \n

sed -e 's/<[^/]/\n</g'

它明显输出的唯一问题

\n<uration>89</duration>

这让我想到了我的问题。我如何告诉 regex 为

【问题讨论】:

    标签: regex bash shell unix


    【解决方案1】:
     echo "<duration>89</duration>" | sed -E 's/<([^\/])/\\n<\1/g'
    

    应该这样做。

    示例运行

    $ echo "<duration>89</duration>
    > <tag>Some Stuff</tag>"| sed -E 's/<([^\/])/\\n<\1/g'
    \n<duration>89</duration>
    \n<tag>Some Stuff</tag>
    

    【讨论】:

      【解决方案2】:

      试试这个:

      sed -e 's/<[^/]/\\n&/g' file
      

      sed -e 's/<[^/]/\n&/g' file
      

      &amp;: 引用模式空间中匹配的那部分

      【讨论】:

      • 不错。 -E 选项更便携恕我直言
      【解决方案3】:

      awk 可以很好地完成:

      echo '<duration>89</duration>' | awk '1' RS='<' ORS='\n<'
      
      • RS='&lt;' sets the input record separator to
      • ORS='\n&lt;' sets the output record separator to\n
      • 1 总是评估为真。没有指定后续操作的真实条件告诉 awk 打印记录。

      【讨论】:

        【解决方案4】:
        echo '<duration>89</duration>' | awk '{sub(/<dur/,"\\n<dur")}1'
        \n<duration>89</duration>
        

        【讨论】:

          【解决方案5】:

          你的说法是正确的,有一个小问题。 sed 替换整个模式,甚至是您设置的任何条件。因此,[^/] 条件语句也被替换。您需要保留这部分,因此您可以尝试以下两种语句中的任何一种:

          sed -e 's/<\([^/]\)/\n<\1/g' file
          

          或如赛勒斯所指出的那样

          sed -e 's/<[^/]/\n&/g' file
          

          干杯!

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2012-02-12
            • 1970-01-01
            • 1970-01-01
            • 2023-03-22
            • 1970-01-01
            • 1970-01-01
            • 2016-07-17
            相关资源
            最近更新 更多