Home > Programming > How to update a xml with shell script ?

How to update a xml with shell script ?

Hey guys, do you remember the script to create xml with shell script ?

Today I will post an example of shell script to update tags in xml file. I used the script in the bottom link as base.


This is the xml that I used as example:


<?xml version="1.0" encoding="ISO-8859-1"?>
<goodnews>
 
 <to>Rafaela</to>
 <from>Br Bank</from>
 <date>04/01/2007</date>
 <amount>$1000,000.00</amount>
 <account>0024549Y48K3-843</account>
 <message>We are pleased to inform you that the above amount was transferred 
to your bank account</message>
 
</goodnews>  

 

And this is the script:

# !/bin/bash
# Written by rafazzevedo
# http://www.azevedorafaela.wordpress.com

# Uncomment this if you want to use parameters given by #the user and change the variables for the parameters #position like: $1 is the first parameter, $2 is the #second. Instead of tag, xml_file...
# if [ $# -ne 3 ]; then
# echo 1>&2 "Please, use the parameters file, tag and new value."
# exit 127
# fi

xml_file="goodnews.xml"
tag="amount"
new_value="\$1000,000.00"

# We will create a temporary file, just to not modify directly the original one.
temporary="temp_file.temp"

# This space is just to identify the end of the xml.
echo " ">> $xml_file

# Extracting the value from the <$tag> element
tag_value=$(grep "<$tag>.*<.$tag>" $xml_file | sed -e "s/^.*<$tag/<$tag/" | cut -f2 -d">"| cut -f1 -d"<")

echo "Found tag value $tag_value..."

# Replacing element value with $new_value
sed -e "s/<$tag>$tag_value<\/$tag>/<$tag>$new_value<\/$tag>/g" $xml_file > $temporary

echo "Changing $tag to $new_value..."

# Updating the changes to the original file ($xml_file)
chmod 666 $xml_file
mv $temporary $xml_file

Thank you guys ! See you soon 🙂

Source: http://www.dotkam.com/2007/04/04/sed-to-parse-and-modify-xml-element-nodes/

http://stackoverflow.com/questions/19951369/how-to-store-grep-command-result-in-some-variable-in-shell

Advertisements
  1. raji
    September 19, 2017 at 6:46 am

    This was very useful to me. Thanks a lot for the post.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: