2

I want to replace one string with another but I can't. The code is:

updatedb
MCRYPTINI=$(locate mcrypt.ini | grep 'apache2')
MCRYPTSO=$(locate mcrypt.so | grep "/mcrypt.so")

OLD="extension=mcrypt.so"
NEW="extension=$MCRYPTSO"

echo $MCRYPTINI
echo $MCRYPTSO
echo $OLD
echo $NEW
echo "'s/$OLD/$NEW' $MCRYPTINI"

sed -i 's/$OLD/$NEW' $MCRYPTINI

And the result is:

sudo sh testScript.sh
/etc/php5/apache2/conf.d/20-mcrypt.ini
/usr/lib/php5/20121212/mcrypt.so
extension=mcrypt.so
extension=/usr/lib/php5/20121212/mcrypt.so
's/extension=mcrypt.so/extension=/usr/lib/php5/20121212/mcrypt.so' /etc/php5/apache2/conf.d/20-mcrypt.ini
sed: -e expression #1, char 11: unterminated `s' command

For the response I don't need to use 'sed', but it's looks easy and good. I use sh not bash because I want the code can use in all the systems, so I prefer answers that follow that principle

UPDATE

sed -i "s/$OLD/$NEW/" $MCRYPTINI

error:

sed: -e expression #1, char 14: unknown option to `s'
  • Have you already tried adding a `/` after `$NEW` in `sed` expression? – Danibix Jul 31 '17 at 08:28
  • Ok, that's resolved the problem... But the string didn't change –  Jul 31 '17 at 08:35
  • Possible duplicate of [Use a variable in a sed command](https://stackoverflow.com/questions/11146098/use-a-variable-in-a-sed-command) – Danibix Jul 31 '17 at 08:41

2 Answers2

1

Add a slash and double quotes:

sed -i  "s/$OLD/$NEW/" file
Guru
  • 16,456
  • 2
  • 33
  • 46
  • The last slash is correct, but with double quotes--> sed: -e expression #1, char 34: unknown option to `s' –  Jul 31 '17 at 08:36
  • @oootramas : The last slash was missing in your snippet. And the double quotes also to be added. – Guru Jul 31 '17 at 08:39
0

The solution could be:

sed -i "s/$OLD/$NEW/" $MCRYPTINI

but $NEW is a path, so I need to change "/" by other character, for example "+"

sed -i "s+$OLD+$NEW+" $MCRYPTINI