http://www.perlmonks.org?node_id=721825

techie411 has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to do a Perl one-liner to replace ONLY the last </TABLE> Tag and replace it with something. I tried the following, but it doesn't work:

 perl -pi -e 's/.*<\/TABLE>/REPLACE/' test.htm

The following doesn't just match the last one but also replaces another </TABLE> tag. Any assistance appreciated. Thanks.

Replies are listed 'Best First'.
Re: Match last instance of pattern
by JStrom (Pilgrim) on Nov 05, 2008 at 22:22 UTC
    No need to involve the regex engine.

    perl -0777 -pe "substr $_, rindex($_,'</TABLE>'), 8, 'REPLACE'" x.html

Re: Match last instance of pattern
by moritz (Cardinal) on Nov 05, 2008 at 21:59 UTC
    If you run perl 5.10.0 or later, you can use this regex: s/.*\K<\/TABLE>/REPLACE/

    If you're not that fortunate, you could use captures: s/(.*)<\/TABLE>/${1}REPLACE/

Re: Match last instance of pattern
by GrandFather (Saint) on Nov 05, 2008 at 22:41 UTC

    Is there only one line in the file you are processing? If not you have something of a problem because the substitution is applied to each line in the file.


    Perl reduces RSI - it saves typing
Re: Match last instance of pattern
by ccn (Vicar) on Nov 05, 2008 at 21:59 UTC

    perl -0777 -pe '$_=reverse;s{>ELBAT/<}{ECALPER};$_=reverse' test.htm

      Are the two reverses (and backward words) better to use than just matching everything before the last </table>?

      perl -0777 -pe 's!(.*)</table>!${1}REPLACE!s;' test.htm

        It depends... How do you compare one JAPH with another?