0

similar to these questions:

In a file like this:

define('_DB_NAME_', 'anything');
define('_DB_USER_', 'something else');
define('_DB_PASSWD_', 'and another value');

how to use sed to replace the value anything, something and another (which are unknown) by refering to the key values _DB_NAME_, _DB_USER_ and _DB_PASSWD?

Community
  • 1
  • 1
François Romain
  • 13,617
  • 17
  • 89
  • 123
  • Do you want to replace the second argument of the first line, or do you want to replace the `'anything'` argument wherever it appears? – Beta Nov 14 '16 at 02:25
  • I want to replace the value `anything` (which is unknown) depending on the key `_DB_NAME_` – François Romain Nov 14 '16 at 02:28

3 Answers3

1

You probably want:

sed -E "
  s/('_DB_NAME_', ')[^']+/\1ABC/
  s/('_DB_USER_', ')[^']+/\1DEF/
  s/('_DB_PASSWD_', ')[^']+/\1GHI/
"

I think awk is more readable:

awk -F "'" -v OFS="'" '
    $2 == "_DB_NAME_"   {$4 = "ABC"}
    $2 == "_DB_USER_"   {$4 = "DEF"}
    $2 == "_DB_PASSWD_" {$4 = "GHI"}
    {print}
'
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
1
sed "s/\(define('_DB_NAME_', \).*/\1'new value');/" filename

and likewise for the other two.

If you want to alter the file in place, you can use -i, but you have to be careful, different versions of sed handle that differently.

Beta
  • 96,650
  • 16
  • 149
  • 150
0
sed -i -e 's/anything/newanything/g;s/something/newthing/g;s/another/newanother/' tempfile

Where tempfile contains that code you had. Output looks like this

define('_DB_NAME_', 'newanything');
define('_DB_USER_', 'newthing else');
define('_DB_PASSWD_', 'and newanother value');
davidejones
  • 1,869
  • 1
  • 16
  • 18