xpt
xpt

Reputation: 23054

awk, skip current rule upon sanity check

How to skip current awk rule when its sanity check failed?

{
  if (not_applicable) skip;
  if (not_sanity_check2) skip;
  if (not_sanity_check3) skip;
  # the rest of the actions
}

IMHO, it's much cleaner to write code this way than,

{
  if (!not_applicable) {
    if (!not_sanity_check2) {
      if (!not_sanity_check3) {
      # the rest of the actions
      }
    }
  }
}

1;

I need to skip the current rule because I have a catch all rule at the end.

UPDATE, the case I'm trying to solve.

There is multiple match point in a file that I want to match & alter, however, there's no other obvious sign for me to match what I want. hmmm..., let me simplify it this way, I want to match & alter the first match and skip the rest of the matches and print them as-is.

Upvotes: 1

Views: 129

Answers (2)

Ed Morton
Ed Morton

Reputation: 204310

I'm really not sure what you're trying to do but if I focus on just that last sentence in your question of I want to match & alter the first match and skip the rest of the matches and print them as-is. ... is this what you're trying to do?

{ s=1 }
s && /abc/ { $0="uvw"; s=0 }
s && /def/ { $0="xyz"; s=0 }
{ print }

e.g. to borrow @Ravinder's example:

$ cat Input_file
9
29

$ awk -v var='10' '
    { s=1 }
    s && ($0<var) { $0="Line " FNR " is less than var";    s=0 }
    s && ($0>var) { $0="Line " FNR " is greater than var"; s=0 }
    { print }
' Input_file
Line 1 is less than var
Line 2 is greater than var

I used the boolean flag variable name s for sane as you also mentioned something in your question about the conditions tested being sanity checks so each condition can be read as is the input sane so far and this next condition is true?.

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133700

As far as I understood your requirement, you are looking for if, else if here. Also you could use switch case available in newer version of gawk packages too.

Let's take an example of a Input_file here:

cat Input_file
9
29

Following is the awk code here:

awk -v var="10" '{if($0<var){print "Line " FNR " is less than var"} else if($0>var){print "Line " FNR " is greater than var"}}' Input_file

This will print as follows:

Line 1 is less than var
Line 2 isgreater than var

So if you see code carefully its checking:

  • First condition if current line is less than var then it will be executed in if block.
  • Second condition in else if block, if current line is greater than var then print it there.

Upvotes: 1

Related Questions