Beefy Boxes and Bandwidth Generously Provided by pair Networks Cowboy Neal with Hat
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Match last instance of pattern

by techie411 (Acolyte)
on Nov 05, 2008 at 21:41 UTC ( #721825=perlquestion: print w/ replies, xml ) Need Help??
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.

Comment on Match last instance of pattern
Download Code
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?
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 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 GrandFather (Cardinal) 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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://721825]
Approved by ccn
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (6)
As of 2014-04-18 03:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (461 votes), past polls