using sed to edit a url string in script

只谈情不闲聊 提交于 2019-12-11 01:55:46

问题


I need to edit these strings in a configuration file

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

I have tried

. 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

In the script the variables are supplied by the variables.sh file. Out come should be

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

回答1:


This does the trick:

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

Output:

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

Regep Explanation:

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 

The tag matching perhaps doesn't need to be so verbose but it's certainly easier for a beginner to understand.

Edit:

If you want to change the <service> port then try this:

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


来源:https://stackoverflow.com/questions/13574397/using-sed-to-edit-a-url-string-in-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!