简体   繁体   English

sed用引号和IP地址替换字符串

[英]sed replace a string with quotes and an IP address

I am attempting to set up a docker container who's IP address and port for a db may change. 我正在尝试设置一个Docker容器,其db的IP地址和端口可能会更改。 On startup of the container I want to use "sed" to replace the previous IP address with the new one. 在启动容器时,我想使用“ sed”将以前的IP地址替换为新的IP地址。

The string to be replaced looks like this (the IP and port could be any valid IP4 IP): 要替换的字符串如下所示(IP和端口可以是任何有效的IP4 IP):

'dbhost' => '172.17.0.2:3306',

If I can switch it to this: 如果可以将其切换为此:

'dbhost' => '$MYSQL_PORT_3306_TCP_ADDR:$MYSQL_PORT_3306_TCP_PORT',

Then I can simply do another sed like this: 然后,我可以像这样简单地做另一个sed:

sed -i.bak 's|$MYSQL_PORT_3306_TCP_ADDR:$MYSQL_PORT_3306_TCP_PORT|'"$MYSQL_PORT_3306_TCP_ADDR:$MYSQL_PORT_3306_TCP_PORT"'|g' /config/www/config/config.php

But I assume the sed commands could also be combined somehow. 但是我认为sed命令也可以以某种方式组合。 I found documentation on using sed on an IP address but not ignoring the quotes around 'dbhost' 我找到了有关在IP地址上使用sed的文档,但没有忽略'dbhost'周围的引号

Any help would be greatly appreacated 任何帮助将不胜感激

Got your points, here is the fix 明白了,这就是解决方法

cat file
'dbhost' => '$MYSQL_PORT_3306_TCP_ADDR:$MYSQL_PORT_3306_TCP_PORT',

MYSQL_PORT_3306_TCP_ADDR=172.17.0.2
MYSQL_PORT_3306_TCP_PORT=3306

sed  "s|\$MYSQL_PORT_3306_TCP_ADDR:\$MYSQL_PORT_3306_TCP_PORT|$MYSQL_PORT_3306_TCP_ADDR:$MYSQL_PORT_3306_TCP_PORT|" file

'dbhost' => '172.17.0.2:3306',
sed -i.bak "/^'dbhost' =>/ s|^.*$|'dbhost' => '$MYSQL_PORT_3306_TCP_ADDR:$MYSQL_PORT_3306_TCP_PORT',|" /config/www/config/config.php
  • for all lines which start ( ^ ) with the string 'dbhost' => 对于所有以(' ^ host)开头的字符串'dbhost'=>的行
  • substitute ( s ) the line from the beginning ( ^ ) to the end ( $ ) with what you want it to look like 替补( s )从一开始(行^ )到结束( $ ),你想要什么样子

This will blindly replace all lines starting with 'dbhost' => . 这将盲目替换以'dbhost' =>开头的所有行。 If there are multiple such lines and you only want to replace a specific one, then you'll need to know the old values for TCP_ADDR and TCP_PORT. 如果有多个这样的行,而您只想替换特定的行,那么您将需要知道TCP_ADDR和TCP_PORT的旧值。

And do make sure you're using doble quotes for the sed command itself, not single ones. 并确保您对sed命令本身使用双引号,而不是单引号。 Otherwise the shell will not replace the variables with their values. 否则,外壳程序将不会用其值替换变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM