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

Hi all I have a shell script that uses perl to do a find/replace on a file, like this

perl -pi -e "s/searchpattern/replacepattern/" filename

My problem is that I only want this to occur at the nth occurence of the file, like this:

junk
junk
replace pattern (this needs to be replaced)
replace pattern
junk

Is there a perl setting that I can use so that only "replace pattern (line 3)" is used, and the "replace pattern" on line 4 is ignored?
Thanks
Joe

Replies are listed 'Best First'.
Re: Doing a find/replace on the nth line
by BrowserUk (Patriarch) on Oct 05, 2004 at 20:16 UTC

    for just the third line

    perl -pi -e "$.== 3 and s/searchpattern/replacepattern/" filename

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
    "Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon
Re: Doing a find/replace on the nth line
by Limbic~Region (Chancellor) on Oct 05, 2004 at 20:03 UTC
    jdev20,
    You can use $. (see perldoc perlvar) and the modulus operator (% - see perldoc perlop).
    perl -pi -e "s/searchpattern/replacepattern/ if $. % 3 == 0" filename
    That will apply the search/replace on every 3rd line.

    Cheers - L~R

Re: Doing a find/replace on the nth line
by ikegami (Patriarch) on Oct 05, 2004 at 21:15 UTC

    You've asked to substitue the nth occurance, and you've asked to substitute the occurance on the nth line. You've been provided with a solution the latter; what follows is solution to the former.

    perl -pi -e "s/searchpattern/replacepattern/ if (/searchpattern/ && ++$match==3)" filename

    hum, let's eliminate the redundancy:

    perl -pi -e "substr($_,$-[0],$+[0]-$-[0], 'replacepattern') if (/searchpattern/ && ++$match==3)" filename