使用 sed 命令查找並取代 xml 檔案中的字元不起作用

使用 sed 命令查找並取代 xml 檔案中的字元不起作用

我有一個名為 myfile.xml 的 xml 文件

<!--This is an xml document for test-->
<a><!--This is root node-->
   <b>
     <c>Hi&Welcome</c>
   </b>
   <d>Hello & How are you?</d>
</a>

我想要這個轉變

<!--This is an xml document for test-->
<a><!--This is root node-->
   <b>
     <c>Hi&amp;Welcome</c>
   </b>
   <d>Hello &amp; How are you?</d>
</a>

我使用 sed 命令如下將所有出現的 & 更改為 &

sed -i 's:&:&amp;:' myfile.xml

但我收到“未定義標籤'yfile.xml'”錯誤。我無法繼續下去。這個怎麼做?

答案1

如果你沒有GNU sedsed需要一個參數-i

sed -i.bak 's:&:&amp;:' myfile.xml

備份檔案是個好主意,或者…

…使用 Perl;)

測試用

perl -pe 's/&/&amp;/' myfile.xml

並製作一個就地編輯

perl -pi -e 's/&/&amp;/' myfile.xml

但只有一次。

命令後的內容myfile.xml

<!--This is an xml document for test-->
<a><!--This is root node-->
   <b>
     <c>Hi&amp;Welcome</c>
   </b>
   <d>Hello &amp; How are you?</d>
</a>

答案2

由於特殊字符,您需要轉義 & 。你需要兩次通過才能完成它。

使用:
1 sed 's|Hi\&|Hi\&amp;|g' yourfile.xml..這將產生:

<!--This is an xml document for test-->
<a><!--This is root node-->
   <b>
     <c>Hi&amp;Welcome</c>
   </b>
   <d>Hello & How are you?</d>
</a>
  1. 第二遍將是:sed 's|Hello\ \&| \Hello\ \&amp;|g' test.xml。生產:

    <!--This is an xml document for test-->
    <a><!--This is root node-->
       <b>
        <c>Hi&amp;Welcome</c>
       </b>
       <d> Hello &amp; How are you?</d>
    </a>
    

    當然使用-iswitch使其永久化。

另一種基於@terdon評論的高級方法是:

sed -e 's/Hello &/Hello \&amp;/' -e 's/Hi&/Hi\&amp;/' filename.xml

相關內容