iugurbas
iugurbas

Reputation: 3

How do I replace a word in a line contains square brackets and dollar signs using sed?

I want to replace in /usr/share/phpmyadmin/config.inc.php file

$cfg['blowfish_secret'] = '';

to

$cfg['blowfish_secret'] = 'blablabla';

with sed.

I am trying this:

sed -i "s/\$cfg['blowfish_secret'] = '';/$cfg['blowfish_secret'] = 'blablabla';/g" /usr/share/phpmyadmin/config.inc.php

but it doesn't change. How can I do this?

Upvotes: 0

Views: 1260

Answers (2)

potong
potong

Reputation: 58420

This might work for you (GNU sed):

sed 's/\(\$cfg\['\''blowfish_secret'\''\] = '\''\)\('\'';\)/\1blablabla\2/' file

This is a good example of:

For the third problem; most people (it seems) prefer to surround the whole of the sed command by double quotes. This solves the problem of single quotes but opens up a side effect that the command can be interpreted by the shell. If you are sure that these side effects will not rear their ugly head (variables and shell history can catch one out) go ahead, but by surrounding the sed command by single quotes and:

  • replacing a single quote by '\''
  • inserting \ before any literal [,],*,^,$ and \

will most likely, save the day.

Upvotes: 1

Dennis Williamson
Dennis Williamson

Reputation: 360085

You need to do some more escaping:

sed -i "s/\$cfg\['blowfish_secret'\] = '';/\$cfg['blowfish_secret'] = 'blablabla';/" /usr/share/phpmyadmin/config.inc.php

Since your command is in double quotes to accommodate the single-quoted strings in the data, you will need to escape both dollar signs so that $cfg doesn't get interpreted as a variable by the shell.

You need to escape the square brackets on the left hand side so the enclosed string isn't treated as a bracket expression (group of characters to match) by sed.

Upvotes: 3

Related Questions