简体   繁体   中英

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. On startup of the container I want to use "sed" to replace the previous IP address with the new one.

The string to be replaced looks like this (the IP and port could be any valid 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 -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. I found documentation on using sed on an IP address but not ignoring the quotes around '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' =>
  • substitute ( s ) the line from the beginning ( ^ ) to the end ( $ ) with what you want it to look like

This will blindly replace all lines starting with '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.

And do make sure you're using doble quotes for the sed command itself, not single ones. Otherwise the shell will not replace the variables with their values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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