Linux – SED Find & Replace w\ Regular Expressions

greplinuxsed

Alright, So i'm confused & out of ideas.

I'm trying to replace all the old IP addresses with a new one.

find -type f | grep \.php$ | xargs sed -r -i "s/(\'|\")(localhost|127.0.0.1|10.0.32.4|10.0.32.5)(\'|\")/\"10.0.32.165\"/g"

I'm trying to find, all the PHP files, and replace any of the following (localhost, 127.0.0.1, 10.0.32.4, 10.0.32.5) with 10.0.32.165.

find * | grep \.php$ | xargs egrep "(\'|\")(localhost|127.0.0.1|10.0.32.4|10.0.32.5)(\'|\")"

After the first command is run, I want to make sure there's no traces of old values left, so i run the above command, but it unfortunately returns

siteeval/application/libraries/fetcher.url.class.php:    $this->host = "10.0.32.4";

Anyone see what i'm doing wrong? or maybe can clue me into a better way of doing this?

Best Answer

Try this:

sed -e 's/\(127\.0\.0\.1\|10\.0\.32\.4\|localhost\|10\.0\.32\.5\)/10.0.32.165/g'

You need to escape the parenthesis and the pipes. If you want to make sure they are always between quotes, try:

sed -e 's/\"\(127\.0\.0\.1\|10\.0\.32\.4\|localhost\|10\.0\.32\.5\)\"/10.0.32.165/g'

Testing it a bit:

$ echo '"10.0.32.4"' | sed -e 's/\"\(127\.0\.0\.1\|10\.0\.32\.4\|localhost\|10\.0\.32\.5\)\"/10.0.32.165/g'
10.0.32.165
$ echo '"localhost"' | sed -e 's/\"\(127\.0\.0\.1\|10\.0\.32\.4\|localhost\|10\.0\.32\.5\)\"/10.0.32.165/g'
10.0.32.165

A suggestion for the future. Always try first with small samples (using echo like this), before moving to the complicated case.

*Edit: Escaped the dots too.

Related Topic