🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: alt.lang.awk
Article #36

Re: How do I skip first match??

#36
From: Jim Monty
Date: Thu, 31 May 2001 07:04
33 lines
2198 bytes
essbee <spare_brain@yahoo.com> wrote:
> Newbie help required for awk in skipping the first match.
>
> I have a file that has two occurrences of "while(1)". I need to skip the
> first one and replace the second one with "while (x>MAXLOOP)" - how can I
> accomplish this? Pl note that the number of lines between the two "while"
> occurrences is not same for all files being processed.

But the first and second occurrences of "while(1)" will always be
on different lines, right? (Pretty safe assumption, I think.)

Set a counter to 1 at the first occurrence of the substring, then
set it to 2 at the second occurrence and perform the substitution:

    # untested
    {
        if (matches == 0 && /while\(1\)/)
            matches = 1
        else if (matches == 1 && sub(/while\(1\)/, "while (x>MAXLOOP)"))
            matches = 2

        print
    }

This technique exploits awk's short-circuit evaluation of compound
conditional expressions to minimize the amount of regular expression
pattern matching performed. (There's no need to keep looking for
the substring "while(1)" after you've seen it the second time.)

-- 
Jim Monty
monty@primenet.com
Tempe, Arizona USA
Technical Details
Message-ID: <9f4qdt$8tp$1@nnrp1.phx.gblx.net>
Path: arc1-ca.pugleaf.net!archiver1.google.com!newsfeed.google.com!newsfeed.stanford.edu!bloom-beacon.mit.edu!news-out.cwix.com!newsfeed.cwix.com!sjc-peer.news.verio.net!news.verio.net!nntp.primenet.com!nntp.gblx.net!news.phx.gblx.net!monty
References: <kmkR6.54300$t12.4285836@bgtnsc05-news.ops.worldnet.att.net>

Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit
X-Google-Thread: 10ad19,8420015e5e3d2662
X-Google-Attributes: gid10ad19,public
X-Google-Thread: 109023,8420015e5e3d2662
X-Google-Attributes: gid109023,public
X-Google-Thread: 116030,8420015e5e3d2662
X-Google-Attributes: gid116030,public
X-Google-ArrivalTime: 2001-05-30 23:34:06 PST
Path: arc1-ca.pugleaf.net!archiver1.google.com!newsfeed.google.com!newsfeed.stanford.edu!bloom-beacon.mit.edu!news-out.cwix.com!newsfeed.cwix.com!sjc-peer.news.verio.net!news.verio.net!nntp.primenet.com!nntp.gblx.net!news.phx.gblx.net!monty
From: Jim Monty <monty@primenet.com>
Newsgroups: alt.lang.awk,comp.lang.awk,fj.comp.lang.awk
Subject: Re: How do I skip first match??
Date: 31 May 2001 07:04:29 GMT
Organization: Primenet
Lines: 33
Message-ID: <9f4qdt$8tp$1@nnrp1.phx.gblx.net>
References: <kmkR6.54300$t12.4285836@bgtnsc05-news.ops.worldnet.att.net>
NNTP-Posting-Host: usr06.primenet.com
X-Complaints-To: abuse@gblx.net
X-Posted-By: monty@206.165.6.206 (monty)