0

have a file call config.php which contains something like this.

<?php
$main="dev.digin.io";

What I need to do is, Whatever the string values which contain after $main= need be replaced with a content in a shell variable like $MainDomain.

Final config.php need to be like this. (consider bash shell variable consist some this like $MainDomain=prod.mail.com )

<?php
$main="prod.mail.com";

2 Answers2

0

@Daz, could you please try following and let me know if this helps you.

 awk -vVAR="$MainDomain" '/\$mainDomain/{sub(/=.*/,"="VAR,$0);} 1' Input_file

Where -vVAR="$MainDomain" VAR is awk's variable which has shell variable named MainDomain's value in it. In awk we can't directly shell variable values so this is how we could assign it to a variable of awk and get it used into it.

Let me know if you have any queries on same.

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
0

This nasty-looking sed substitution gets you what you want:

$ MainDomain=prod.mail.com
$ sed -E "s/^(\\\$main=\")[^\"]+(\";)$/\1$MainDomain\2/" config.php
<?php
$main="prod.mail.com";

Add the -i switch to edit the file "in-place". Use -i.bak to create a backup file config.php.bak.

It looks as though the best thing to do in this situation would be to use a configuration file and adjust your PHP code to read from it, as modifying source code like this is a risky business.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
  • I tired `sed -i "s/^(\\\$mainDomain=\")[^\"]+(\";)$/\1$MainDomain\2/" /var/www/html/include/config.php` it prints the below in the shell prompt. Any idea ? **sed: -e expression #1, char 49: invalid reference \2 on `s' command's RHS** –  Dec 27 '16 at 12:16
  • You're not using the `-E` switch, which means that capture groups need to be escaped. Add the `-E` switch. Also, you should really be using a backup suffix with `-i`, especially when testing. – Tom Fenech Dec 27 '16 at 12:19
  • Then it will print the correct out put ot the console. But not modifying the file. Any idea ? –  Dec 27 '16 at 12:27
  • Use both switches! – Tom Fenech Dec 27 '16 at 12:29
  • Thanks @Tom it works ! –  Dec 27 '16 at 12:32