Erick
Erick

Reputation: 368

sed regex with replace

Given a file:

<?

$dbo = mysql_fetch_assoc();

$dbo->employee_id;

$dbo->employee_name;

$dbo->dirt;

$dbo->dirt23;

$dbo->dirt_2_3;

?>

and using sed to find and replace:

sed -e "s|$dbo->([\w\_]*)|$dbo['\1']|g" test.php

It always returns an error. I've tried using apostrophes as container and escaping everything properly and using forward slash as the command delimiter, but to no avail.

Result should be:

<?

$dbo = mysql_fetch_assoc();

$dbo['employee_id'];

$dbo['employee_name'];

$dbo['dirt'];

$dbo['dirt23'];

$dbo['dirt_2_3'];

?>

Help, please.

Upvotes: 3

Views: 212

Answers (4)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

You can use this perhaps (basic mode):

sed "s/\$dbo->\([^;]\+\)/\$dbo['\1']/" file.php

Upvotes: 0

anubhava
anubhava

Reputation: 785256

Few mistakes:

  1. \w already includes underscore
  2. $ needs to be excaped
  3. Square brackets need to be excaped
  4. You're using $ inside double quotes while be expanded by shell

Use following sed:

sed -r 's/(\$dbo->)([[:alnum:]_]+)(.*)$/\1["\2"]\3/g'

OR on OSX:

sed -E 's/(\$dbo->)([[:alnum:]_]+)(.*)$/\1["\2"]\3/g'

For Using single quotes:

sed -r "\$s/(dbo->)([a-zA-Z0-9_]+)(.*)$/\1['\2']\3/g"

Upvotes: 3

Adi Inbar
Adi Inbar

Reputation: 12323

You're escaping one character that doesn't need to be escaped, and not escaping another character that does need to be escaped. The _ is not a regex metacharacter, but the $ is (matches the end of the string). Make that:

sed -e "s|\$dbo->([\w_]*)|$dbo['\1']|g" test.php

BTW, it's the \_ that's generating the error. The unescaped $ wouldn't give you an error, it would just make the regex fail to ever match anything, because you're trying to match the end of the string and then some things after the end. But \_ doesn't mean anything; it would have to be either \\_ to include both backslash and underscore in the character class, or just _ to include just underscore.

Upvotes: 0

ennuikiller
ennuikiller

Reputation: 46965

If you are using Mac OSX you need the -E switch instead of -e, and use the following command instead of what you have:

cat test.php | sed -E "s/dbo->([a-z_]*.*);/dbo[\'\1\']/g"

Upvotes: 0

Related Questions