[英]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
) 我想将文本
PATHTOEXPORT
替换为在命令行中传递的变量的内容,该变量中将包含文件夹路径(例如/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. 我碰到了这篇文章 ,讨论了如何使用
sed
将XML文件中的值替换为另一个。
However, not having used sed
before, I'm unsure how to read the directions. 但是,由于以前没有使用过
sed
,所以我不确定如何阅读说明。
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?
我可以就地执行此操作,而不使用中间文件吗?
You can have sed edit in place. 您可以将sed编辑到位。 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有两个选项,一个是sed为您创建一个临时文件(最安全),另一个是真正地对其进行了编辑(如果未测试您的命令,则很危险)。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.