Replacing a *specific* term in an XML file

I want to replace the text PATHTOEXPORT with the contents of a variable passed on the command-line that would have a folder path in it (for example, /Dev_Content/AIX/Apache)

I came across this article that discusses how to use sed to replace a value in an XML file with another.

However, not having used sed before, I'm unsure how to read the directions.

The script is as follows:

# 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

Is there a better way to do what I need to do? Can I do it in situ rather than using an intermediate file?

Answers


You can have sed edit in place. There are two options, have sed make a temporary file for you (safest) or really have it edit in place (dangerous if your command isn't tested).

sed -i 'bak' -e 's|PATHTOEXPORT|/Dev_Content/AIX/Apache|' file.txt

or for the brave:

sed -i '' -e 's|PATHTOEXPORT|/Dev_Content/AIX/Apache|' file.txt

Need Your Help

ImageAnimator.StopAnimate() doesn't appear to actually do anything

c# system.drawing

I'm working with the ImageAnimator object for the first time and finding that a call to StopAnimate() doesn't appear to actually stop the underlying thread from running and calling the FrameChanged

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.