Shaw
Shaw

Reputation: 1139

AWK-Printing a line as the first record in an output file

Heres the problem:

I have an AWK script which is scheduled to run every day via a crontab entry. This particular script outputs errors to an error log. I have a variable which increments every time an error is encountered and have the following control statement at the end of my script:

if (blErrorCounter) {
    print "Log contains " blErrorCounter " errors!"
} else {
    print "Log contains no errors!"
}

The script contains a number of other error handling conditions which output data to the log file, but I want to be able to print the above as the very first record in the file...

It maybe something simple as I'm a noob to AWK but any help/pointer would be greatly received.

Shaw

Upvotes: 0

Views: 103

Answers (1)

Ed Morton
Ed Morton

Reputation: 203522

You need to save the error messages to print in the END section, e.g.:

/error/ { errors[++blErrorCounter] = "Got error at line " FNR }
END {
    if (blErrorCounter) {
        print "Log contains", blErrorCounter, "errors!"
        for (ec=1; ec <= blErrorCounter; ec++) {
            print errors[ec]
        }
    } else {
        print "Log contains no errors!"
    }
}

You could write that a bit briefer too:

/error/ { errors[++blErrorCounter] = "Got error at line " FNR }
END {
    print "Log contains", (blErrorCounter ? blErrorCounter : "no"), "errors!"
    for (ec=1; ec <= blErrorCounter; ec++) {
        print errors[ec]
    }
}

Or even just live with "0" instead of the word "no":

/error/ { errors[++blErrorCounter] = "Got error at line " FNR }
END {
    printf "Log contains %d errors!\n", blErrorCounter
    for (ec=1; ec <= blErrorCounter; ec++) {
        print errors[ec]
    }
}

Upvotes: 4

Related Questions