Awk: catch `exit 'in END block

I use awkto format the input file in the output file. I have several templates for populating variables (for example, "some template" in the example). These variables are printed in the required format in the block END. The result must be done there, because the order of appearance in the input file is not guaranteed, but the order in the output file must always be the same.

BEGIN {
    FS = "=|,"
}


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

END {
    # Output the variables
    print var
}

, - exit . , , , , . gawk () , exit , END . exit :

if (!exit_invoked) {
    print var
}

- END?

edit: shellter.

+5
2

, exit_invoked exit, ..

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

, .

+6
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.

      ......
-2

All Articles