紹介する
スクリプト:
sed -i '1i <?xml version=\"1.0\" encoding=\"utf-8\"?>' $1
sed -i '/<?xml version=\"1.0\" encoding=\"utf-8\"?>/a<hello>\n\t<world>' $1
sed -i "\$a\\\t<\/hello>\n<\/world>" $1
入力する:
<city id="city01">
<name>utrecht</author>
<population>328.577</population>
<districts>10</districts>
<country>netherlands</country>
</city>
出力:
<?xml version="1.0" encoding="utf-8"?>
<hello>
<world>
<city id="city01">
<name>utrecht</author>
<population>328.577</population>
<districts>10</districts>
<country>netherlands</country>
</city>
</hello>
</world>
質問
sedを使用するよりもファイルをラップするより簡単な方法は何ですか?
ベストアンサー1
私の意見で述べたように、実際の問題が何であるかを理解していません。以下は、sed
スクリプト機能を実行するいくつかのきちんとした方法です。
$ printf "%s\n%s\n\t%s\n%s\n%s\n%s\n" '<?xml version="1.0" encoding="utf-8"?>' \
'<hello>' '<world>' "$(cat file)" "</world>" "</hello>"
<?xml version="1.0" encoding="utf-8"?>
<hello>
<world>
<city id="city01">
<name>utrecht</author>
<population>328.577</population>
<districts>10</districts>
<country>netherlands</country>
</city>
</world>
</hello>
または
$ echo -e '<?xml version="1.0" encoding="utf-8"?>' "\n<hello>\n<world>" "$(cat file)" \
"</world>\n</hello>"
<?xml version="1.0" encoding="utf-8"?>
<hello>
<world> <city id="city01">
<name>utrecht</author>
<population>328.577</population>
<districts>10</districts>
<country>netherlands</country>
</city> </world>
</hello>
または
$ perl -lpe 'BEGIN{
print "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<hello>\n\t<world>"
}
$_="\t\t$_"; END{print "\t </world>\n</hello>"}' file
<?xml version="1.0" encoding="utf-8"?>
<hello>
<world>
<city id="city01">
<name>utrecht</author>
<population>328.577</population>
<districts>10</districts>
<country>netherlands</country>
</city>
</world>
</hello>
ファイルの内部編集を使用できますperl -i -ple
。
または
$ awk 'BEGIN{printf "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<hello>\n\t<world>";}
{print "\t\t",$0}END{printf "\t </world>\n</hello>\n"}' file
<?xml version="1.0" encoding="utf-8"?>
<hello>
<world> <city id="city01">
<name>utrecht</author>
<population>328.577</population>
<districts>10</districts>
<country>netherlands</country>
</city>
</world>
</hello>
または混合物:
$ echo -e '<?xml version="1.0" encoding="utf-8"?>\n<hello>\n\t<world>';
perl -pe '$_="\t\t$_"' file; echo -e "</world>\n</hello>"
<?xml version="1.0" encoding="utf-8"?>
<hello>
<world>
<city id="city01">
<name>utrecht</author>
<population>328.577</population>
<districts>10</districts>
<country>netherlands</country>
</city>
</world>
</hello>