我想在命令行傳遞一個變量的內容,將有一個文件夾路徑替換文本PATHTOEXPORT
(例如,/Dev_Content/AIX/Apache
)在一個XML文件
更換*具體*項我遇到了這個article,它討論瞭如何使用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會寫入stdout,因此您必須將其捕獲到臨時文件中。如果您嘗試在原始文件中捕獲該文件,您將覆蓋文件並丟失內容。 – GreenMatt 2010-10-27 19:26:32
@GreenMatt謝謝 – warren 2010-10-27 19:49:03
糟糕!我忘記了-i選項,因爲我從不使用它,對不起。大概20年前我第一次學習Unix時,我不認爲sed有過這種情況(如果我明顯沒有學過它),那麼我腦海中的一點記憶似乎就是ROM! ; - >正如Brian Clements在回答中所說的那樣,它有可能破壞文件,所以我建議使用後綴進行備份。 – GreenMatt 2010-10-27 21:04:50