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"?>
 <from>Br Bank</from>
 <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

#Β 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


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

# 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 πŸ™‚


2 thoughts on “How to update a xml with shell script ?

Leave a Reply

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

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

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.