如何使用 sed (Jenkinsfile) 在我的 xml 文件的结束标记上方插入文本?

How to insert text above the close tag of my xml file using sed (Jenkinsfile)?

我有changelog_master.xml如下:

<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
   http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd">

  <include file="changelog/version/changelog_1.0.xml"/>

</databaseChangeLog>

我想像这样在文件的结束标记上方插入文本

 <databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
   http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd">

  <include file="changelog/version/changelog_1.0.xml"/>
  <include file="changelog/version/changelog_1.1.xml"/>

</databaseChangeLog>

我试过像这样使用 sed,因为我需要将它写在 Jenkinsfile 中以实现自动化

sh "sed -i '/<\/databaseChangelog>/i <include file=\"changelog/version/changelog_${version}.xml\"/>' changelog/changelog_master.xml"

但它不起作用。我也尝试了许多相关问题。

我现在该怎么办?

谢谢!

在 XML 具有命名空间的文件中添加一个子节点并使用 xmlstarlet 插入一个属性:

xmlstarlet edit \
  --omit-decl -N x="http://www.liquibase.org/xml/ns/dbchangelog" \
  --subnode "//x:databaseChangeLog" -t elem -n "include" \
  --insert "//x:databaseChangeLog/include" -t attr -n "file" --value "changelog/version/changelog_1.1.xml" file.xml

输出到标准输出:

<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog    http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd">
  <include file="changelog/version/changelog_1.0.xml"/>
  <include file="changelog/version/changelog_1.1.xml"/>
</databaseChangeLog>

如果您想就地编辑文件,请添加选项 -L。

参见:xmlstarlet edit --help

sed 也可以,这是我的版本(您的匹配模板中有错字)

 $ sed -i "/<\/databaseChangeLog>/i\<include file=\"changelog/version/changelog_${version}.xml\"/>" changelog/changelog_master.xml