Miserable Variable
Miserable Variable

Reputation: 28761

process at top level without reading next line

Is there a way to start processing at top level again? next does this but it also reads a line from input. I want to do it without reading another line.

My use-case is that when I see line matching pattern1 I want to stop processing until I see a line matching pattern2. If there was an ungetline I would have done

/pattern1/ {
   getline;
   while (! /pattern2/ ) { getline; }
   ungetline; }

I could be stuck in procedural approach

Upvotes: 0

Views: 104

Answers (1)

Scheff's Cat
Scheff's Cat

Reputation: 20141

To solve the case you described I would use the folling approach:

BEGIN { skip = 0 }

/pattern1/ { skip = 1 ; next }

skip && /pattern2/ { skip = 0 }

!skip && /text/ {
  print "Found text which is not between pattern1 and pattern2"
  next
}

!skip {
  print $0
}

The !skip enables last two rules only if skipis 0.

But this should work also:

BEGIN { skip = 0 }

/pattern1/ { skip = 1 ; next }

skip && /pattern2/ { skip = 0 }

skip { next }

/text/ {
  print "Found text which is not between pattern1 and pattern2"
  next
}

{ # else...
  print $0
}

Notes:

  1. pattern2 is processed in the above examples. (Place a next into its action if this is not desired.)

  2. The BEGIN rule is actually not necessary but somehow nice to document the special meaning of the skip variable.

Upvotes: 1

Related Questions