I'm trying to replace a text string in an XML file with another using the sed tool command , but I can't get the result I expect.
Command:
sed -i -e -r 's|test-plugin.+\s\s*?<version>(.+)<\/version>|test-plugin.+\s\s*?<version>1.0.0<\/version>|g' plugins.xml
XML:
<plugins>
<plugin>
<name>test-plugin</name>
<version>3.0.0-SNAPSHOT</version>
</plugin>
<plugin>
<name>test-plugin-2</name>
<version>3.0.0-SNAPSHOT</version>
</plugin>
<plugin>
<name>test-plugin-3</name>
<version>2.0.0-SNAPSHOT</version>
</plugin>
</plugins>
The result I expect is that it replaces the version of the first plugin since it is the one that matches the name given in the command itself. Obviously, replace it respecting the line breaks and spaces of the XML structure.
Thank you very much in advance.
Right now I can't think of a shorter version with
awk
, but it would definitelysed
be an unnecessary pain.Try this:
What I do here is that when I find the name of the plugin, I assign a 1 to the "seen" variable (that is, I set it to True), then I print the line and ask
awk
it to see the next line, and then, if variableseen
is True (has the value 1), substitute the version number and then set the variable to falseseen
.With the number 1, there alone, I only ask you to print the line by default, which by now will have already been modified or will be any other that does not meet the conditions of the regex.
update
Since I decided to do it with
sed
, this would be the answer:What we do is that the name of the plugin will cause whatever is between the braces {} to be executed.
And what is between the curly braces is:
The truth was not as much pain as I thought it would be.
I tried to help you using
regex
but it can be quite complex and difficult to maintain since it would not be as flexible to changes (something you have to take into account), evenawk
though it is much more powerful thansed
, what you can do is generate a script in python so that it does what you need. I leave you the code (personally I prefer the 2 version of this example):1st version
you can save it with any name, for this example save it as
nombre_del_script.py
and call it like this:You can also receive the file path and version by console, in that case I would change the code to:
2nd version
and calls it like this (obviously changes to the corresponding values):