Sample Header Ad - 728x90

Make awk produce error on non-numeric

5 votes
5 answers
1658 views
I have a program that sums a column in a file: awk -v col=2 '{sum+=$col}END{print sum}' input-file However, it has a problem: If you give it a file that doesn't have numeric data, (or if one number is missing) it will interpret it as zero. I want it to produce an error if one of the fields cannot be parsed as a number. Here's an example input: bob 1 dave 2 alice 3.5 foo bar I want it to produce an error because 'bar' is not a number, rather than ignoring the error.
Asked by Nick ODell (2798 rep)
Jan 16, 2019, 05:18 PM
Last activity: Jul 14, 2023, 11:11 AM