4

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.

1 Answer 1

6

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|"
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks ! I'm using this script in a jenkins and i can't get the value of $ver. I always write me '' $ver '' in my xml file. Is there a way to indicate directly the variable in the command line ? ( And sometimes, this variable could be a path, so how to deal with the slash problems ? )
@MxfrdA you must double quote "$ver" to expand the variable.
Thanks, first problem resolved, I can see my variable. But when it's a path, the script doesn't pass and get : sed: -e expression n°1, caractère 53: option inconnue pour `s' . Sorry my Jenkins is in French
Or edit my xml like this : <version>/path/to/fix/CHANGE.XML</version> i just need to change the CHANGE.XML in this path
Perfect ! Thanks you for taking time to help me :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.