0

I'm new to Sed and as you might imagine you can get lost early ...

I have the following variable in a PHP page I'm trying to change using a bash script:

$username='';

I want to give it an expanded variable value stored in $myUsername so that the final entry looks like:

$username='someName';

I believe I'm close with the following, but can't seem to cross that finish line ...

sed -i 's/"$username = ''".*$/\$username = /"${myUsername}/"' /var/www/settings.php

Thanks for the education / help

Mark
  • 610
  • 9
  • 22
  • 1
    Why do you have all the double quotes inside the regex? `sed` will try to match those and fail. – lurker Apr 09 '14 at 13:09
  • possible duplicate of [shell variables in sed script](http://stackoverflow.com/questions/7006910/shell-variables-in-sed-script) – devnull Apr 09 '14 at 13:11
  • Note that this is fine for usernames, but won't work if you have data containing the `/` character; more involved techniques are necessary to work with arbitrary data. – Charles Duffy Apr 09 '14 at 13:41
  • (also, `sed -i` is not a POSIX-standard option, so don't be surprised if scripts in which you use it don't work on other operating systems). – Charles Duffy Apr 09 '14 at 13:41
  • Thank you all for the additional comments, much appreciated. – Mark Apr 09 '14 at 17:19

1 Answers1

1

You are almost there, use for example this improved version:

sed -i "s/\$username = ''/\$username = '$myUsername'/" file

Note that to use a variable you need to use double quotes. Otherwise, the variable won't be expanded. Also, that's why escaping $username with \$username is needed, to avoid it being interpreted as the bash variable $username.

Test

$ cat a
hello
$username = '';
bye

$ myUsername="bu"
$ sed "s/\$username = ''/\$username = '$myUsername'/" a
hello
$username = 'bu';
bye

$ myUsername="hello"
$ sed "s/\$username = ''/\$username = '$myUsername'/" a
hello
$username = 'hello';
bye

Improvement

You can also improve the approach by catching a block. It works with \( block \) syntax, printing it back with \1:

$ sed "s/\(\$username = \)''/\1'$myUsername'/" a
hello
$username = 'hello';
bye
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 1
    Thanks so much. I knew about the " for expansion and thought I was indeed close. Much appreciated. – Mark Apr 09 '14 at 13:21