Search code examples
if-statementawkskip

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.


Solution

  • 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.