1

I'm trying to come up with a sed script to modify the constructors in a couple hundred php files from php4 style to php5 style. I'm making some progress, but I'm having a problem with getting the back references out of sed. Here is an example file :

<?php

class Dashboard extends CI_Controller {

    function Dashboard()
    {
        parent::Controller();   
    }
}

The goal is to grab the class name from the first line (which will have 0 or 1 blank lines between it and the

This works as expected:

sed -En '/^class\ ([a-zA-Z0-9]+)/ {
    n;H;x;n;H;x;'s/Dash/Derp/';P
}' dashtest.php

Giving the output:

function Derpboard()

But why is this not replacing Dashboard with __construct?:

sed -En '/^class\ ([a-zA-Z0-9]+)/ {
    n;H;x;n;H;x;'s/\1/__construct/';P
}' dashtest.php

Any other advice on this would be welcome. My intention is to wrap this in a shell script that is making a bunch of other changes migrating from an ancient version of codeIgnitor php framework the current version.

1 Answer 1

0

The ' you have just before s/… exits single-quote mode, causing the whole s/\1/__construct/ (up to the next ') to be parsed as unquoted by your shell. In this mode, \1 gets translated to just 1, so sed ends up receiving s/1/__construct/.

Note that this would not work anyway, because backreferences in POSIX regexes used by sed can only refer to groups within the same regexp, and sed has no special syntax for using previous matches.

You would need something more advanced – for example:

perl -pe '
    if (/^class (\w+)/) {
        $class = $1;
    }
    elsif (/^\}$/) {
        $class = "";
    }
    elsif ($class and /function \Q$class\E\(/) {
        s//function __construct(/;
    }
'
1
  • I see. I was hoping to hone my rather lacking sed-fu with this task, but it looks like I'll go for brushing up on Perl instead. This example is only the first of several modifications that I'll need to make, and I will definitely need to store some matches for later use. Thank you. Oct 21, 2013 at 19:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .