2012-11-26 95 views
2

一個URL字符串,我需要在配置文件中使用的sed編輯腳本

<port>8189</port> 
<service>127.0.0..1:8190</service> 
<wan-access>localhost</wan-access> 

編輯這些字符串我試圖

. variables.sh 

cat config.sh | 
    sed -i.bk \ 
    -e 's/\<^port\>\/'$port'/\<\/\port\>/' \ 
    -e 's/\<^service\>\/'$url'/\<\/\service\>/' \ 
    -e 's/\<^wan-access\>\/'$url2'/\<\/\wan-access\>/' config.sh 

在變量來對這些變量提供的腳本。 sh文件。 出落得應該

<port>8787</port> 
<service>my.domain.com:8190</service> 
<wan-access>my.realdomain.com</wan-access> 
+0

沒有必要逃避尖括號。我不明白你想用'^'字符做什麼。 '^'表示輸入的開始,所以它會導致您嘗試使用它的方式出現問題。 – jahroy

回答

1

該做的伎倆:

port=8787 
url="my.domain.com" 
url2="my.realdomain.com" 

sed -i.bk -Ee "s/(<port>)[0-9]+(<\/port)/\1${port}\2/" \ 
    -e "s/(<service>)[^:]*(:.*)/\1${url}\2/" \ 
    -e "s/localhost/${url2}/" config.sh 

輸出:

<port>8787</port> 
<service>my.domain.com:8190</service> 
<wan-access>my.realdomain.com</wan-access> 

Regep說明:

s/   # The first substitution 
(<port>) # Match the opening port tag (captured) 
[0-9]+  # Match the port number (string of digits, at least one) 
(<\/port) # Match the closing port tag (captured, escaped forwardslash) 
/   # Replace with 
\1   # The first capture group 
${port}  # The new port number 
\2   # The second capture group 

s/   # The second substitution 
(<service>) # Match the opening service tag (captured) 
[^:]*  # Match anything not a : 
(:.*)  # Match everything from : (captured) 
/   # Replace with 
\1   # The first capture group 
${url}  # The new url 
\2   # The second capture group 

s/   # The third substitution 
localhost # Match the literal string 
/   # Replace with 
${url2}  # The other new url 

標籤也許匹配並不需要如此冗長,但初學者理解起來肯定更容易。

編輯:

如果你想改變<service>端口,然後試試這個:

-e "s/(<service>).*(<\/service)/\1${url}:${port}\2/" 
+0

首先感謝代碼。它在第二行上生成my.domain.com:8787:8190。當然你可以看到太多的端口。有什麼想法嗎? – user1846439

+0

我在哪裏可以瞭解更多關於sed的信息? – user1846439

+0

我已經有sed通過sed管道sed的一個多年的習慣。我喜歡使用-e選項。 – ddoxey