MxfrdA
MxfrdA

Reputation: 171

Edit xml file shell script

I want to edit a xml file using a shell script.

i've got something like this

<version>1.7.21</version>

And i want my script to edit the .xml file like this, using a variable

ex : $value = 3.2 '' command to change the xml file '' and get this :

<version>3.2</version>

I've been looking on the web but nothing works for me ..

Edit: I'm looking for a generic way.

For example the solution of this post : How to change specific value of XML attribute using scripting on Mac

isn't what i'm looking for, because it depends of the previous xml file.

Upvotes: 4

Views: 10455

Answers (1)

SLePort
SLePort

Reputation: 15461

With sed :

$ ver=3.2;
$ sed "s/\(<version>\)[^<]*\(<\/version>\)/\1$ver\2/" <<< "<version>1.7.21</version>"
<version>3.2</version>

To apply it to file :

$ ver=3.2;
$ sed -i "s/\(<version>\)[^<]*\(<\/version>\)/\1$ver\2/" file

The -i option is for editing the file in place.

Update :

To apply a sed command to a path, you must either escape the slashes in the path :

ver="\/path\/to\/fix\/CHANGE.XML";

or change the sed separator with a character you won't find in your path. Example with | :

sed "s|\(<version>\)[^<]*\(<\/version>\)|\1$ver\2|"

Upvotes: 6

Related Questions