
我有一個名為 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&Welcome</c>
</b>
<d>Hello & How are you?</d>
</a>
我使用 sed 命令如下將所有出現的 & 更改為 &
sed -i 's:&:&:' myfile.xml
但我收到“未定義標籤'yfile.xml'”錯誤。我無法繼續下去。這個怎麼做?
答案1
如果你沒有GNU sed,sed
需要一個參數-i
sed -i.bak 's:&:&:' myfile.xml
備份檔案是個好主意,或者…
…使用 Perl;)
測試用
perl -pe 's/&/&/' myfile.xml
並製作一個就地編輯和
perl -pi -e 's/&/&/' myfile.xml
但只有一次。
命令後的內容myfile.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>
答案2
由於特殊字符,您需要轉義 & 。你需要兩次通過才能完成它。
使用:
1 sed 's|Hi\&|Hi\&|g' yourfile.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>
第二遍將是:
sed 's|Hello\ \&| \Hello\ \&|g' test.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>
當然使用
-i
switch使其永久化。
另一種基於@terdon評論的高級方法是:
sed -e 's/Hello &/Hello \&/' -e 's/Hi&/Hi\&/' filename.xml