我正在尝试使用 bash 编辑配置文件。我的文件如下所示:
<configuration>
<property>
<name></name>
<value></value>
</property>
<property>
<name></name>
<value></value>
</property>
</configuration>
我想再添加一对 <property>
block 到文件。由于所有property
标签包含在 configuration
中标记文件看起来像这样:
<configuration>
<property>
<name></name>
<value></value>
</property>
<property>
<name></name>
<value></value>
</property>
<property>
<name></name>
<value></value>
</property>
</configuration>
我遇到了 this post and followed the accepted answer ,但是我的文件没有附加任何内容,我尝试附加的 xml block 被“回显”为单行字符串。 我的 bash 文件如下所示:
file=/path/to/file/oozie-site.xml
content="<property>\n<name></name>\n<value></value>\n</property>\n<property>\n<name></name>\n<value></value>\n</property>"
echo $content
C=$(echo $content | sed 's/\//\\\//g')
sed "/<\/configuration>/ s/.*/${C}\n&/" $file
最佳答案
使用 xmlstarlet:
xmlstarlet edit --omit-decl \
-s '//configuration' -t elem -n "property" \
-s '//configuration/property[last()]' -t elem -n "name" \
-s '//configuration/property[last()]' -t elem -n "value" \
file.xml
输出:
<configuration>
<property>
<name/>
<value/>
</property>
<property>
<name/>
<value/>
</property>
<property>
<name/>
<value/>
</property>
</configuration>
--omit-decl
: omit XML declaration
-s
: add a subnode (seexmlstarlet edit
for details)
-t elem
: set node type, here: element
-n
: set name of element
关于xml - Bash 将子节点插入到 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42962889/