Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to edit XML using bash script?

Tags:

bash

sh

parsing

xml

<root>
<tag>1</tag>
<tag1>2</tag1>
</root>

Need to change values 1 and 2 from bash

like image 341
Roman Avatar asked Jul 29 '11 12:07

Roman


People also ask

How can I edit an XML file?

XML files can also be edited using your computer's notepad program and even with certain word processing and spreadsheet programs. However, XML editors are considered advantageous because they are able to validate your code and ensure you remain within a valid XML structure.

How do I edit an XML file in Ubuntu?

To edit any config file, simply open the Terminal window by pressing the Ctrl+Alt+T key combinations. Navigate to the directory where the file is placed. Then type nano followed by the filename that you want to edit. Replace /path/to/filename with the actual file path of the configuration file that you want to edit.


2 Answers

To change tag's value to 2 and tag1's value to 3, using XMLStarlet:

xmlstarlet ed \
  -u '/root/tag' -v 2 \
  -u '/root/tag1' -v 3 \
  <old.xml >new.xml

Using your sample input:

xmlstarlet ed \
  -u '/root/tag' -v 2 \
  -u '/root/tag1' -v 3 \
  <<<'<root><tag>1</tag><tag1>2</tag1></root>'

...emits as output:

<?xml version="1.0"?>
<root>
  <tag>2</tag>
  <tag1>3</tag1>
</root>
like image 100
Charles Duffy Avatar answered Sep 19 '22 17:09

Charles Duffy


Since you give a sed example in one of the comments, I imagine you want a pure bash solution?

while read input; do
  for field in tag tag1; do
    case $input in
      *"<$field>"*"</$field>"* )
        pre=${input#*"<$field>"}
        suf=${input%"</$field>"*}
        # Where are we supposed to be getting the replacement text from?
        input="${input%$pre}SOMETHING${input#$suf}"
        ;;
    esac
  done
  echo "$input"
done

This is completely unintelligent, and obviously only works on well-formed input with the start tag and the end tag on the same line, you can't have multiple instances of the same tag on the same line, the list of tags to substitute is hard-coded, etc.

I cannot imagine a situation where this would be actually useful, and preferable to either a script or a proper XML approach.

like image 41
tripleee Avatar answered Sep 21 '22 17:09

tripleee