
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
しかし、「undefined label '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
特殊文字のため、& を脱出する必要があります。完了するには 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>
2 回目のパスは次のようになります:
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
永続的にするにはスイッチを使用します。
以下の @terdon のコメントに基づいたもう 1 つの高度な方法は次のとおりです。
sed -e 's/Hello &/Hello \&/' -e 's/Hi&/Hi\&/' filename.xml