Leticia Esperon Leticia Esperon - 19 days ago 7
Linux Question

Editing xml from script

I need to run a user-data script in an ec2-instance that changes an XML in a folder.

I have an XML like this one in a path in the ec2:

<Root>
<Properties>
<Property>
<Name>myProp</Name>
<Value>old_value</Value>
</Property>
<Property>
<Name>anotherProp</Name>
<Value>other_value</Value>
</Property>
</Propierties>
</Root>


I want to change old_value into new_value. But just that one, not other_value.

How can I do this?

I've tried a powershell script but I don't know how to run it to test it:

#!/bin/bash
$path = '/home/wowza/conf/Server.xml'

$new_value = 'new_value'

$xml = [xml](Get-Content $path)

$xml.Data.Course.Subject

$property = $xml.Root.Server.Properties.Property | where {$_.Name -eq 'myProp'}
$property.Value = $new_value

$xml.Save($path)


Please if you send me a script don't forget to include how to run it to test it, the interpreter for the #! line and what things to install.
Thank you!

Answer

The code below will allow you to set the new_value for the targeted field even if you don't know what the old_value is:

#!/bin/bash

sed -i -e '/<Name>myProp<\/Name>/,/<Value>/s/^\s*<Value>.*$/<Value>new_value<\/Value>/' /folder/xml-file

The only caveat here is that the script will strip white space indentations from the line to be changed, but that is only a visual thing that does not affect the code result; you can add the indentation spaces you need afterwards with another sed command, if that is important to you.

Comments