使用sed在脚本中编辑url字符串 [英] using sed to edit a url string in script

查看:110
本文介绍了使用sed在脚本中编辑url字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在配置文件中编辑这些字符串

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>

我尝试过

. 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

在脚本中,变量由variables.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>


推荐答案

这可以解决问题:

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> 端口,请尝试以下操作:

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

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

这篇关于使用sed在脚本中编辑url字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆