tags:

views:

72

answers:

2

I've got a large number of PHP files and lines that need to be altered from a standard echo "string goes here"; syntax to: custom_echo("string goes here");

This is the line I'm trying to punch into Perl to accomplish this: perl -pi -e 's/echo \Q(.?*)\E;/custom_echo($1);/g' test.php Unfortunately, I'm making some minor syntax error, and it's not altering "test.php" in the least. Can anyone tell me how to fix it?

+2  A: 

You put your grouping parentheses inside the metaquoting expression (\Q(pattern)\E) instead of outside ((\Qpattern\E)), so your parentheses also get escaped and your regex is not capturing anything.

mobrule
Did you get inside and outside backwards?
Matt Kane
Well, that's one less problem, but I still seem to have more issues.
Harold Hardrada
@Matt Kane don't think so ... I meant this to parse as "You put them inside but you should have put them outside"
mobrule
Oh, sorry, I didn't realize that the outer set of parens was not meant to part of code section.
Matt Kane
+4  A: 

Why not just do something like:

perl -pi -e 's|echo (\".*?\");|custom_echo($1);|g' file.php

I don't think \Q and \E are doing what you think they're doing. They're not beginning and end of quotes. They're in case you put in a special regex character (like .) -- if you surround it by \Q ... \E then the special regex character doesn't get interpreted.

In other words, your regular expression is trying to match the literal string (.?*), which you probably don't have, and thus substitutions don't get made.

You also had your ? and * backwards -- I assume you want to match non-greedily, in which case you need to put the ? as a non-greedy modifier to the .* characters.

Edit: I also strongly suggest doing:

perl -pi.bak -e ... file.php

This will create a "backup" file that the original file gets copied to. In my above example, it'll create a file named file.php.bak that contains the original, pre-substitution contents. This is incredibly useful during testing until you're certain that you've built your regex properly. Hell, disk is cheap, I'd suggest always using the -pi.bak command-line operator.

CanSpice
Thank you! Exactly what I was ham-handedly trying to get to. And I always rsync my data before making any major changes like this. :)
Harold Hardrada