Mickey
Mickey

Reputation: 53

replace a line that contains a string with special characters

i want to replace lines which contains a string that has some special characters. i used \ and \ for escape special characters but nothing changes in file. i use sed like this:

> sed -i '/pnconfig\[\'dbhost\'\] = \'localhost\'/c\This line is removed.' tco.php

i just want to find lines that contains :

$pnconfig['dbhost'] = 'localhost';

and replace that line with:

  $pnconfig['dbhost'] = '1.1.1.1';

Upvotes: 2

Views: 136

Answers (4)

Karthikeyan.R.S
Karthikeyan.R.S

Reputation: 4041

Try this one.

sed "/$pnconfig\['dbhost']/s/localhost/1.1.1.1/"

Upvotes: 0

Arjun Mathew Dan
Arjun Mathew Dan

Reputation: 5298

You don't have to worry about backslashing single quotes by using double quotes for sed.

sed -i.bak "/pnconfig\['dbhost'\] = 'localhost'/s/localhost/1.1.1.1/g" File

Upvotes: 0

nu11p01n73R
nu11p01n73R

Reputation: 26667

Wrap the sed in double quotes as

sed -i "s/\(pnconfig\['dbhost'\] = \)'localhost'/\1'1.1.1.1'/" filename

Test

$ echo "\$pnconfig['dbhost'] = 'localhost';" | sed "s/\(pnconfig\['dbhost'\] = \)'localhost'/\1'1.1.1.1'/"
$pnconfig['dbhost'] = '1.1.1.1';

Upvotes: 1

SMA
SMA

Reputation: 37023

Use as below:

sed -i.bak '/pnconfig\[\'dbhost\'\] = \'localhost\'/pnconfig\[\'dbhost\'\] = \'1.1.1.1\'/' tco.php

Rather than modifying the file for the first time, create back up and then search for your pattern and then replace it with the other as above in your file tco.php

Upvotes: 0

Related Questions