不要使用SED XML解析,因爲它不是設計來處理XML的語法,寫在SED的XML解析器是一項艱鉅的任務。此外,還有許多有用的工具可以用於此目的。
考慮這個XML:
<root>
<item>
<errorCode>4000</errorCode>
<severity>2</severity>
<modelDescription>Some error</modelDescription>
</item>
<item>
<errorCode>4544</errorCode>
<severity>4</severity>
<modelDescription>Licensing: Invalid license</modelDescription>
</item>
</root>
您可以輕鬆地xmlstarlet
修改severity
值:
xmlstarlet ed -u '//item[severity = 4
and modelDescription = "Licensing: Invalid license"]/severity' \
-v 100 file.xml
命令更新(-u
)通過更換原值severity
元素的值(4
)與100
。 XPath表達式爲所有item
元素選擇severity
元素,其中severity
子值爲4
和modelDescription
子值爲Licensing: Invalid license
的子元素。
結果打印到標準輸出。要就地編輯文件,請使用--inplace
選項:xmlstarlet ed --inplace -u ...
。
輸出
<?xml version="1.0"?>
<root>
<item>
<errorCode>4000</errorCode>
<severity>2</severity>
<modelDescription>Some error</modelDescription>
</item>
<item>
<errorCode>4544</errorCode>
<severity>100</severity>
<modelDescription>Licensing: Invalid license</modelDescription>
</item>
</root>
請不要使用「巨大」之類的術語。使用數字(我們畢竟是工程師)。這可能會影響答案。 –