views:

39

answers:

1

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?

+1  A: 

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
Brian Clements
I should also note that the direct option has the potential to corrupt the file if something goes wrong.
Brian Clements
That's just what I was looking for! Thanks :)
warren