Linux 使用sed在脚本中编辑url字符串
我需要在配置文件中编辑这些字符串Linux 使用sed在脚本中编辑url字符串,linux,string,bash,sed,edit,Linux,String,Bash,Sed,Edit,我需要在配置文件中编辑这些字符串 <port>8189</port> <service>127.0.0..1:8190</service> <wan-access>localhost</wan-access> 8189 127.0.0..1:8190 本地服务器 我试过了 . variables.sh cat config.sh | sed -i.bk \ -e 's/\<^port\>\/'$po
<port>8189</port>
<service>127.0.0..1:8190</service>
<wan-access>localhost</wan-access>
8189
127.0.0..1:8190
本地服务器
我试过了
. 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
cat config.sh|
sed-i.bk\
-e's/\\/'$port'/\/'\
-e's/\\/'$url'/\/'\
-e's/\\/'$url2'/\/'config.sh
在脚本中,变量由variables.sh文件提供。
结果应该是
<port>8787</port>
<service>my.domain.com:8190</service>
<wan-access>my.realdomain.com</wan-access>
8787
my.domain.com:8190
my.realdomain.com
这就做到了:
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
url=“my.domain.com”
url2=“my.realdomain.com”
sed-i.bk-Ee“s/()[0-9]+(没有必要跳过尖括号。我不明白您试图对^
字符执行什么操作。^
表示输入的开始,因此它会在您尝试使用它的方式中造成问题。首先感谢代码。它在第二行my.domain.com:8787:8190上生成。当然,您可以看到这一点。)太多的端口了。有什么想法吗?我有一个多年的习惯,通过sed管道传输sed。我喜欢使用-e选项。查看我的编辑,应该可以解决您的问题。这里是一个学习、阅读问题、提问、尝试内容以及sed
和regex
的在线教程的好地方。谢谢您的教程建议。我会的我更深入地了解了这个网站。代码现在运行良好。非常感谢你的解释。没问题,如果你能对答案投赞成票,那就太好了。
<port>8787</port>
<service>my.domain.com:8190</service>
<wan-access>my.realdomain.com</wan-access>
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
-e "s/(<service>).*(<\/service)/\1${url}:${port}\2/"