[英]Un-commenting xml block using sed command
我有其中注釋了許多元素的xml文件。 從所有這些元素中,我想使用sed命令取消注釋一個元素。
我有xml文件為:
<!-- This is the sample xml
which holds the data of the students -->
<Students>
<!-- <student>
<name>john</>
<id>123</id>
</student> -->
<student>
<name>mike</name>
<id>234</id>
</student>
<!-- <student>
<name>NewName</name>
<id>NewID</id>
</student> -->
</Students>
在上面的xml文件中,我想取消注釋最后一個xml塊,所以我的文件看起來像
<!-- This is the sample xml
which holds the data of the students -->
<Students>
<!-- <student>
<name>john</>
<id>123</id>
</student> -->
<student>
<name>mike</name>
<id>234</id>
</student>
<student>
<name>NewName</name>
<id>NewID</id>
</student>
</Students>
我經歷了sed命令,但沒有得到如何從最后一個塊中刪除<!--
和-->
。 是否可以取消注釋<name>
作為NewName
xml塊? 除了刪除整行,我什么也沒找到。
編輯:我可以有許多<name>
和<id>
類的xml元素,例如<address>, <city>, <class>,<marks>
。
不要使用sed
。 使用xsltproc
。
<!-- uncomment.xsl -->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- this copies every input node unchanged -->
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*" />
</xsl:copy>
</xsl:template>
<!-- this uncomments every comment that starts with a `<` -->
<xsl:template match="comment()[substring(normalize-space(), 1, 1) = '<']">
<xsl:value-of select="." disable-output-escaping="yes" />
</xsl:template>
</xsl:stylesheet>
在命令行上:
xsltproc -o output.xml uncomment.xsl input.xml
如果它可以正常工作,則可以通過輸入XML來獲得它:
<!-- This is the sample xml
which holds the data of the students -->
<Students>
<student>
<name>john</name>
<id>123</id>
</student>
<student>
<name>mike</name>
<id>234</id>
</student>
<student>
<name>NewName</name>
<id>NewID</id>
</student>
</Students>
這可能對您有用(GNU sed):
sed -r '/<Students>/,/<\/Students>/{/<Students>/{h;d};H;/<\/Students>/!d;g;s/(.*)<!-- (.*) -->(.*)/\1\2\3/}' file
這會將Students
數據存儲在保留空間中,然后使用貪婪找到<!--
和-->
的最后一次出現,並在打印數據之前將其刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.