简体   繁体   中英

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!

With GNU sed:

sed -i '/<Name>myProp<\/Name>/,/<Value>old_value<\/Value>/s/old_value/new_value/' file.xml

Output to file file.xml:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM