2010-10-27 51 views
1

我想在命令行傳遞一個變量的內容,將有一個文件夾路徑替換文本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 

是否有更好的方法做我需要做什麼?我可以在原位而不是使用中間文件嗎?

+1

是的,你需要一箇中間文件。默認情況下,sed會寫入stdout,因此您必須將其捕獲到臨時文件中。如果您嘗試在原始文件中捕獲該文件,您將覆蓋文件並丟失內容。 – GreenMatt 2010-10-27 19:26:32

+0

@GreenMatt謝謝 – warren 2010-10-27 19:49:03

+0

糟糕!我忘記了-i選項,因爲我從不使用它,對不起。大概20年前我第一次學習Unix時,我不認爲sed有過這種情況(如果我明顯沒有學過它),那麼我腦海中的一點記憶似乎就是RO​​M! ; - >正如Brian Clements在回答中所說的那樣,它有可能破壞文件,所以我建議使用後綴進行備份。 – GreenMatt 2010-10-27 21:04:50

回答

1

您可以在原地進行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 
+1

我還應該注意,如果出現問題,直接選項可能會損壞文件。 – 2010-10-27 19:35:34

+0

這就是我一直在尋找的!謝謝 :) – warren 2010-10-27 19:49:23