Bash add subzone to XML file

I am trying to edit a configuration file using bash. My file is as follows:

<configuration>
  <property>
    <name></name>
    <value></value>
  </property>
  <property>
    <name></name>
    <value></value>
  </property>
</configuration>

I want to add a couple more blocks <property>to the file. Since all tags are propertyenclosed within tags configuration, the file looks like this:

<configuration>
  <property>
    <name></name>
    <value></value>
  </property>
  <property>
    <name></name>
    <value></value>
  </property>
  <property>
    <name></name>
    <value></value>
  </property>
</configuration>

I stumbled upon this post and followed the accepted answer , however, nothing was added to my file, and the xml block that I am trying to add is "echo ed" as a line with one line. My bash file looks like this:

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
+3
source share
2 answers

Using 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

Output:

<configuration>
  <property>
    <name/>
    <value/>
  </property>
  <property>
    <name/>
    <value/>
  </property>
  <property>
    <name/>
    <value/>
  </property>
</configuration>

--omit-decl: omit XML declaration

-s: add a subnode (see details for details ) xmlstarlet edit

-t elem: set node type, here: element

-n:

+5

sed -i.BAK "/<\/configuration>/ s/.*/${C}\n&/" $file

0

Source: https://habr.com/ru/post/1689101/


All Articles