SED to parse and modify XML element nodes

relement.sh:

# Check that exactly 3 values were passed in
if [ $# -ne 3 ]; then
echo 1>&2 “This script replaces xml element’s value with the one provided as a command parameter \n\n\tUsage: $0 <xml filename> <element name> <new value>”
exit 127
fi
 
echo "DEBUG: Starting... [Ok]\n"
echo "DEBUG: searching $1 for tagname <$2> and replacing its value with '$3'"
 
# Creating a temporary file for sed to write the changes to
temp_file="repl.temp"
 
# Elegance is the key -> adding an empty last line for Mr. “sed” to pick up
echo ” ” >> $1
 
# Extracting the value from the <$2> element
el_value=`grep “<$2>.*<.$2>” $1 | sed -e “s/^.*<$2/<$2/” | cut -f2 -d”>”| cut -f1 -d”<”`
 
echo "DEBUG: Found the current value for the element <$2> - '$el_value'"
 
# Replacing elemen’s value with $3
sed -e “s/<$2>$el_value<\/$2>/<$2>$3<\/$2>/g” $1 > $temp_file
 
# Writing our changes back to the original file ($1)
chmod 666 $1
mv $temp_file $1

使用语法:

relement.sh `XML File` `node name` `new node value`

示例:

XML:goodnews.xml

<?xml version="1.0" encoding="utf-8"?>
<goodnews>
	<to>Yanik</to>
	<from>ING Bank</from>
	<date>04/01/2007</date>
	<amount>$1,000,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>
./relement.sh goodnews.xml account my-secure-account
DEBUG: Starting... [Ok]
 
DEBUG: searching goodnews.xml for tagname <account> and replacing its value with 'my-secure-account'
DEBUG: Found the current value for the element <account> - '0024549Y48K3-843'
DEBUG: <account>0024549Y48K3-843</account> was successfully changed to <account>my-secure-account</account>
 
DEBUG: Exiting... [Ok]
cat goodnews.xml
<?xml version="1.0" encoding="utf-8"?>
<goodnews>
	<to>Yanik</to>
	<from>ING Bank</from>
	<date>04/01/2007</date>
	<amount>$1,000,000.00</amount>
	<account>my-secure-account</account>
	<message>We are pleased to inform you that the above amount was transferred to your bank account</message>
</goodnews>


你可能感兴趣的:(SED to parse and modify XML element nodes)