Stefan
Stefan

Reputation: 776

awk: catch `exit' in the END block

I'm using awk for formatting an input file in an output file. I have several patterns to fill variables (like "some pattern" in the example). These variables are printed in the required format in the END block. The output has to be done there because the order of appearance in the input file is not guaranteed, but the order in the output file must be always the same.

BEGIN {
    FS = "=|,"
}


/some pattern/ {
    if ($1 == 8) {
        var = $1
    } else {
        # Incorrect field value
        exit 1
    }
}

END {
    # Output the variables
    print var
}

So my problem is the exit statement in the pattern. If there is some error and this command is invoked, there should be no output at all or at the most an error message. But as the gawk manual (here) says, if the exit command is invoked in a pattern block the END block will be executed at least. Is there any way to catch the exit like:

if (!exit_invoked) {
    print var
}

or some other way to avoid printing the output in the END block?

Stefan

edit: Used the solution from shellter.

Upvotes: 7

Views: 3055

Answers (3)

James Brown
James Brown

Reputation: 37464

Being a fan of short syntax and trying to avoid futile {}s or adding them later to pre-existing programs, instead of:

...
    else {
        exit_invoked=1
        exit 1
    }
...
END {
    if (! exit_invoked  ) {
        print var
    }
}

I use:

    else 
        exit (e=1)            # the point
...
END {
    if(!e)
        print v
}

Upvotes: 0

mjp
mjp

Reputation: 11

END {
      # If here from a main block exit error, it is unlikely to be at EOF
      if (getline) exit 
      # If the input can still be read, exit with the previously set status rather than run the rest of the END block.

      ......

Upvotes: 0

shellter
shellter

Reputation: 37298

you'll have to handle it explicitly, by setting exit_invoked before exit line, i.e.

BEGIN {
    FS = "=|,"
}


/some pattern/ {
    if ($1 == 8) {
        var = $1
    } else {
        # Incorrect field value
        exit_invoked=1
        exit 1
    }
}

END {
    if (! exit_invoked  ) {
        # Output the variables
        print var
    }
}

I hope this helps.

Upvotes: 8

Related Questions