6

Im trying to edit a config file using bash. My file looks like this:

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

I want to add another couple of <property> blocks to the file. Since all property tags are enclosed inside the configuration tags the file would looks like this:

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

I came across this post and followed the accepted answer, however nothing is appended to my file and the xml block I try to append is "echo-ed" as a single line string. 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
1
  • 2
    Use an XML/HTML parser (xmllint, xmlstarlet ...). Commented Mar 22, 2017 at 21:25

2 Answers 2

7

With 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 xmlstarlet edit for details)

-t elem: set node type, here: element

-n: set name of element

Sign up to request clarification or add additional context in comments.

3 Comments

trying this out - when I run this command, it prints out my config file in the terminal with the added subnode. However when I check the file out in vim nothing seems to be appended
Nvm . I added file.xml > newfile.xml and see the changes. thanks a lot. One final question, how to add multiple blocks? just have more these `-s '//configuration/property[last()]' -t elem -n "value" ` ?
If there's a namespace defined, you need to specify it... stackoverflow.com/questions/17615428/…
1

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

1 Comment

Your answer would be more helpful with some explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.