awk:在END块中捕获`exit'

Ste*_*fan 5 awk

awk用于格式化输出文件中的输入文件.我有几种模式来填充变量(例如示例中的"某些模式").这些变量以END块中所需的格式打印.输出必须在那里完成,因为输入文件中的外观顺序不能保证,但输出文件中的顺序必须始终相同.

BEGIN {
    FS = "=|,"
}


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

END {
    # Output the variables
    print var
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是exit模式中的陈述.如果存在某些错误并且调用了此命令,则根本不应该输出或者最多没有错误消息.但正如gawk手册(这里)所说,如果exit在模式块中调用该命令,则END至少会执行该块.有没有办法赶上exit这样的:

if (!exit_invoked) {
    print var
}
Run Code Online (Sandbox Code Playgroud)

或其他一些方法来避免在END块中打印输出?

斯特凡

编辑:使用shellter的解决方案.

she*_*ter 6

你必须通过在行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
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助.