【问题标题】:sed replace multiple xml tagsed替换多个xml标签
【发布时间】:2013-09-27 04:04:30
【问题描述】:

我需要使用 sed 替换 xml 文件中的多行。这是我的输入文件:

<firstTag>Y</firstTag>
<secondTag/>

我想将这些行替换为以下格式:

<firstTag></firstTag>
<secondTag>Y</secondTag>

我尝试使用此命令:

sed -i -r "s#<firstTag>Y</firstTag>\n.*#<firstTag></firstTag>\n<secondTag>Y</secondTag>#g" input.txt

但它不起作用。我还注意到在 secondTag 之前有一些选项卡(^I using less 命令)。它会影响 sed 命令吗?请帮我解决这个问题。

更新:文件中出现了多次secondTag,我只想在发现firstTag的先前值为Y之后才将secondTag值更改为Y。例如,如果在input.txt中:

<firstTag>Y</firstTag>
<secondTag/>
<firstTag/>
<secondTag/>

我希望将其替换为:

<firstTag></firstTag>
<secondTag>Y</secondTag>
<firstTag/>
<secondTag/>

【问题讨论】:

    标签: regex unix sed


    【解决方案1】:

    这可能对你有用(GNU sed):

    sed -r '$!N;s|^(<firstTag>)Y(</firstTag>\n<(secondTag))/>$|\1\2>Y</\3>|;P;D' file
    

    【讨论】:

      【解决方案2】:

      你可以试试这个sed:

      sed -r '/<firstTag>.*<\/firstTag>/{N;s#(<firstTag>)(.*)((</firstTag>\n)<secondTag/>)#\1\4<secondTag>\2</secondTag>#g}' file.txt
      

      【讨论】:

      • 这给出了错误的&lt;secondTag/&gt; 正确的请求是&lt;/secondTag&gt;
      • 谢谢。更新了我的答案。
      【解决方案3】:

      使用awk 你可以这样做:

      awk -F"[<>/]" '/^<firstTag>/ {f=$3;$0="<"$2"></"$2">"} /^<secondTag\/>/ {$0="<"$2">" f "</"$2">"}1' file
      <firstTag><firstTag/>
      <secondTag>Y</secondTag>
      

      关于此评论:

      对不起,我忘了提到有多次出现 secondTag,我只想将 secondTag 值更改为 Y 之后发现firstTag的前一个值为Y

      这是另一个awk,如果有firstTag,则只更改第一个secondTag,忽略所有其他:

      cat file
      <secondTag/>
      <firstTag>Y</firstTag>
      <secondTag/>
      <someOtherTag>
      <secondTag/>
      

      awk

      awk -F"[<>/]" '/^<firstTag>/ {f=$3;$0="<"$2"></"$2">"} f && /^<secondTag\/>/ {$0="<"$2">" f "</"$2">";f=""}1' file
      <secondTag/>
      <firstTag></firstTag>
      <secondTag>Y</secondTag>
      <someOtherTag>
      <secondTag/>
      

      【讨论】:

        【解决方案4】:

        如何将两个标签替换分开?

        sed -i -r -e "s#<firstTag>Y</firstTag>#<firstTag></firstTag>#" -e "s#<secondTag/>#<secondTag>Y</secondTag>#" input.txt
        

        【讨论】:

        • 对不起,我忘了说secondTag多次出现,我只想在发现firstTag的先前值为Y后才将secondTag值更改为Y。
        猜你喜欢
        • 1970-01-01
        • 2017-12-12
        • 2015-10-07
        • 2017-10-07
        • 2019-05-25
        • 1970-01-01
        • 2016-03-13
        • 1970-01-01
        • 2015-08-15
        相关资源
        最近更新 更多