SED config-file with single quote

I have a config file which looks like this:

        $this->db_host = 'localhost';
        $this->db_port = '3306';
        $this->db_name = 'database';
        $this->db_user = 'root';

Im trying to replace the values between the single quotes with sed env-variables I have set but I cant seem to get it working. My sed command looks like this right now.

sed -r -in "s/(db_host *= *\").*/\1$MYSQL_HOST\"/" cfg.php

The $MYSQL_HOST-var contains the following string "db".

The config should look like the following after the successful sed command:

        $this->db_host = 'db';
        $this->db_port = '3306';
        $this->db_name = 'database';
        $this->db_user = 'root';

Maybe you can help me find my error?


This will do it:

sed -r "s/(\s*.*db_host =* *').*('.*)/\1$MYSQL_HOST\2/" your_file

The ways it's working is as follows:

  • I remember the stuff in between the above using ( and )
  • Specifically I remember up to and including the first single quote and also everything after and including the second single quote. So we remember all by the localhost bit.
  • Then replace with the remembered content \1 and \2 and the $MYSQL_HOST going in between

Once you've confirmed it does what you want, just add the -i:

sed -ri "s/(\s*.*db_host =* *').*('.*)/\1$MYSQL_HOST\2/" your_file