簡體   English   中英

在XML文件中替換* specific *術語

[英]Replacing a *specific* term in an XML file

我想將文本PATHTOEXPORT替換為在命令行中傳遞的變量的內容,該變量中將包含文件夾路徑(例如/Dev_Content/AIX/Apache

我碰到了這篇文章 ,討論了如何使用sed將XML文件中的值替換為另一個。

但是,由於以前沒有使用過sed ,所以我不確定如何閱讀說明。

腳本如下:

# 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

有沒有更好的方法來做我需要做的事情? 我可以就地執行此操作而不使用中間文件嗎?

您可以將sed編輯到位。 sed有兩個選項,一個是sed為您創建一個臨時文件(最安全),另一個是真正地對其進行了編輯(如果未測試您的命令,則很危險)。

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

還是勇敢的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM