🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

3 total messages Started by essbee Thu, 31 May 2001 05:09
How do I skip first match??
#35
Author: essbee
Date: Thu, 31 May 2001 05:09
14 lines
1663 bytes
All,

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.

Any help???

Thanks!!

essbee
Re: How do I skip first match??
#36
Author: 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
Re: How do I skip first match??
#37
Author: tt
Date: Thu, 31 May 2001 09:39
17 lines
1795 bytes
"essbee" <spare_brain@yahoo.com> writes:

> 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?

awk '/while\(1\)/ && count++ { sub("while\(1\)","while(x>MAXLOOP)"}'

That will replace all occurrences except the first.
If you want to replace only the second (and skip possible 3rd &c), do

awk '/while\(1\)/ && ++count==2 ... '

-- 
Tapani Tarvainen
Thread Navigation

This is a paginated view of messages in the thread with full content displayed inline.

Messages are displayed in chronological order, with the original post highlighted in green.

Use pagination controls to navigate through all messages in large threads.

Back to All Threads