Make awk produce error on non-numeric












4















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.










share|improve this question


















  • 2





    If not a dupe, at least strongly related: Can I determine type of an awk variable?

    – Kusalananda
    Jan 16 at 17:30











  • by "produce an error", do you mean stop altogether, or skip the line, and/or emit a message?

    – Jeff Schaller
    Jan 16 at 17:39











  • Stop altogether and emit a message.

    – Nick ODell
    Jan 16 at 17:41











  • @Kusalananda Thanks, that was really helpful.

    – Nick ODell
    Jan 16 at 17:54
















4















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.










share|improve this question


















  • 2





    If not a dupe, at least strongly related: Can I determine type of an awk variable?

    – Kusalananda
    Jan 16 at 17:30











  • by "produce an error", do you mean stop altogether, or skip the line, and/or emit a message?

    – Jeff Schaller
    Jan 16 at 17:39











  • Stop altogether and emit a message.

    – Nick ODell
    Jan 16 at 17:41











  • @Kusalananda Thanks, that was really helpful.

    – Nick ODell
    Jan 16 at 17:54














4












4








4








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.










share|improve this question














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.







awk numeric-data






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 16 at 17:18









Nick ODellNick ODell

1,0912920




1,0912920








  • 2





    If not a dupe, at least strongly related: Can I determine type of an awk variable?

    – Kusalananda
    Jan 16 at 17:30











  • by "produce an error", do you mean stop altogether, or skip the line, and/or emit a message?

    – Jeff Schaller
    Jan 16 at 17:39











  • Stop altogether and emit a message.

    – Nick ODell
    Jan 16 at 17:41











  • @Kusalananda Thanks, that was really helpful.

    – Nick ODell
    Jan 16 at 17:54














  • 2





    If not a dupe, at least strongly related: Can I determine type of an awk variable?

    – Kusalananda
    Jan 16 at 17:30











  • by "produce an error", do you mean stop altogether, or skip the line, and/or emit a message?

    – Jeff Schaller
    Jan 16 at 17:39











  • Stop altogether and emit a message.

    – Nick ODell
    Jan 16 at 17:41











  • @Kusalananda Thanks, that was really helpful.

    – Nick ODell
    Jan 16 at 17:54








2




2





If not a dupe, at least strongly related: Can I determine type of an awk variable?

– Kusalananda
Jan 16 at 17:30





If not a dupe, at least strongly related: Can I determine type of an awk variable?

– Kusalananda
Jan 16 at 17:30













by "produce an error", do you mean stop altogether, or skip the line, and/or emit a message?

– Jeff Schaller
Jan 16 at 17:39





by "produce an error", do you mean stop altogether, or skip the line, and/or emit a message?

– Jeff Schaller
Jan 16 at 17:39













Stop altogether and emit a message.

– Nick ODell
Jan 16 at 17:41





Stop altogether and emit a message.

– Nick ODell
Jan 16 at 17:41













@Kusalananda Thanks, that was really helpful.

– Nick ODell
Jan 16 at 17:54





@Kusalananda Thanks, that was really helpful.

– Nick ODell
Jan 16 at 17:54










4 Answers
4






active

oldest

votes


















7














A reasonable way to test would be to compare the field using tests similar to strtod, which is the method that awk uses to convert strings to numbers:



$2 !~ / *[+-]?[[:digit:]]/ { print "NAN: " $2; exit 1; }


The above differs from strtod in that it does not consider INFINITY or NAN to be "numbers". The leading space requirement could be relaxed under awk's default field-splitting behavior -- meaning the fields would never contain leading space:



$2 !~ /[+-]?[[:digit:]]/ { print "NAN: " $2; exit 1; }


A further refinement, thanks to Stéphane's comment and answer here:



$2 !~ /^[+-]?([[:digit:]]*.?[[:digit:]]*([eE][-+]?[[:digit:]]+)?|0[xX][[:xdigit:]]*.?[[:xdigit:]]*([pP][-+]?[[:digit:]]+)?)$/ { print "NAN: " $2; exit 1; }


Broken out for slightly better legibility, that regex is:



/^[+-]?([[:digit:]]*.?[[:digit:]]*([eE][-+]?[[:digit:]]+)?|
0[xX][[:xdigit:]]*.?[[:xdigit:]]*([pP][-+]?[[:digit:]]+)?)$/


... where the intention is to allow a possible leading + or -, then either a floating point number or hexadecimal number. The floating point number has optional leading digits, an option separator (here fixed to be a period .), followed by some number of digits, optionally followed by an exponent. The hex number must start with 0x or 0X, followed by hex digits, a separator, more hex digits, and optionally followed by a "power" (exponent). The entire second field must match one of those formats (as anchored by ^ and $). Omitted here, for the purposes of this question, are the NAN and INFINITY options.



Another option would be to force a numeric conversion, then compare it to zero and then further compare the original input to something that would convert to zero; more specifically, does it start with an optional + or -, then is it followed by zeros, or followed by a period and zeros:



{ number=0 + $2;
if (!number && $2 !~ /^[+-]?(0+)|.0+/)
print "NAN: "$2;
}





share|improve this answer





















  • 1





    You'd need to anchor the regexp (with ^), otherwise, it's just a test whether the second field contains a decimal digit. You'd also need to take care of numbers like .123. There's also whether you want to honour user's decimal radix (comma vs period). The last one would let strings like ., +, +.

    – Stéphane Chazelas
    Jan 16 at 21:49











  • Great points, Stéphane; thank you. I will correct the simpler aspects shortly.

    – Jeff Schaller
    Jan 17 at 0:43











  • notice that when converting strings to numbers awk will ignore any trailing junk (see my answer) and /^[+-]?0*.?0*$/ is far from being a thorough pattern matching strings that will be completely parsed to 0 by strtod (what about 0e13, .0e-0, 0x0, 0x.0p+13, etc?)

    – Uncle Billy
    Jan 17 at 1:58













  • Point well taken, @UncleBilly, as also noted by Stéphane above. I'm working on the "zero" regex right now...

    – Jeff Schaller
    Jan 17 at 2:00



















5














I ended up with this:



awk -v col=$col '
typeof($col) != "strnum" {
print "Error on line " NR ": " $col " is not numeric"
noprint=1
exit 1
}
{
sum+=$col
}
END {
if(!noprint)
print sum
}' $file


This uses typeof, which is a GNU awk extension. typeof($col) returns 'strnum' if $col is a valid number, and 'string' or 'unassigned' if it is not.



See Can I determine type of an awk variable?






share|improve this answer































    2














    awk -v col=2 '
    $col+0==0 && $col!~/^[+-]?0/ { print "bad number " $col > "/dev/stderr" }
    {sum+=$col}
    END{print sum}' input-file


    It's up to you to complicate it if you want it to also handle .0 or .0e+33 as valid representations of 0; notice that awk will ignore trailing junk when converting strings to numbers ("1.4e1e3"+0, "1.4e1.e7"+0 or "14+13"+0 will be all equal to 14).






    share|improve this answer































      1















      If you give it a file that doesn't have numeric data,




      $col ~ /[^-.[:digit:]]/ {print "Error, non-numeric :"; print $col; exit 1};


      Explanation just use a RegEx to check for the presence of characters which are not digits nor floating point, sign, etc.




      (or if one number is missing)




      add



      || ($col == "")


      or



      || (length($col) == 0)


      to the rule.



      Or you could use a comparison to NF if it's the last column like in your example.






      share|improve this answer























        Your Answer








        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "106"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: false,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: null,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f494889%2fmake-awk-produce-error-on-non-numeric%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        7














        A reasonable way to test would be to compare the field using tests similar to strtod, which is the method that awk uses to convert strings to numbers:



        $2 !~ / *[+-]?[[:digit:]]/ { print "NAN: " $2; exit 1; }


        The above differs from strtod in that it does not consider INFINITY or NAN to be "numbers". The leading space requirement could be relaxed under awk's default field-splitting behavior -- meaning the fields would never contain leading space:



        $2 !~ /[+-]?[[:digit:]]/ { print "NAN: " $2; exit 1; }


        A further refinement, thanks to Stéphane's comment and answer here:



        $2 !~ /^[+-]?([[:digit:]]*.?[[:digit:]]*([eE][-+]?[[:digit:]]+)?|0[xX][[:xdigit:]]*.?[[:xdigit:]]*([pP][-+]?[[:digit:]]+)?)$/ { print "NAN: " $2; exit 1; }


        Broken out for slightly better legibility, that regex is:



        /^[+-]?([[:digit:]]*.?[[:digit:]]*([eE][-+]?[[:digit:]]+)?|
        0[xX][[:xdigit:]]*.?[[:xdigit:]]*([pP][-+]?[[:digit:]]+)?)$/


        ... where the intention is to allow a possible leading + or -, then either a floating point number or hexadecimal number. The floating point number has optional leading digits, an option separator (here fixed to be a period .), followed by some number of digits, optionally followed by an exponent. The hex number must start with 0x or 0X, followed by hex digits, a separator, more hex digits, and optionally followed by a "power" (exponent). The entire second field must match one of those formats (as anchored by ^ and $). Omitted here, for the purposes of this question, are the NAN and INFINITY options.



        Another option would be to force a numeric conversion, then compare it to zero and then further compare the original input to something that would convert to zero; more specifically, does it start with an optional + or -, then is it followed by zeros, or followed by a period and zeros:



        { number=0 + $2;
        if (!number && $2 !~ /^[+-]?(0+)|.0+/)
        print "NAN: "$2;
        }





        share|improve this answer





















        • 1





          You'd need to anchor the regexp (with ^), otherwise, it's just a test whether the second field contains a decimal digit. You'd also need to take care of numbers like .123. There's also whether you want to honour user's decimal radix (comma vs period). The last one would let strings like ., +, +.

          – Stéphane Chazelas
          Jan 16 at 21:49











        • Great points, Stéphane; thank you. I will correct the simpler aspects shortly.

          – Jeff Schaller
          Jan 17 at 0:43











        • notice that when converting strings to numbers awk will ignore any trailing junk (see my answer) and /^[+-]?0*.?0*$/ is far from being a thorough pattern matching strings that will be completely parsed to 0 by strtod (what about 0e13, .0e-0, 0x0, 0x.0p+13, etc?)

          – Uncle Billy
          Jan 17 at 1:58













        • Point well taken, @UncleBilly, as also noted by Stéphane above. I'm working on the "zero" regex right now...

          – Jeff Schaller
          Jan 17 at 2:00
















        7














        A reasonable way to test would be to compare the field using tests similar to strtod, which is the method that awk uses to convert strings to numbers:



        $2 !~ / *[+-]?[[:digit:]]/ { print "NAN: " $2; exit 1; }


        The above differs from strtod in that it does not consider INFINITY or NAN to be "numbers". The leading space requirement could be relaxed under awk's default field-splitting behavior -- meaning the fields would never contain leading space:



        $2 !~ /[+-]?[[:digit:]]/ { print "NAN: " $2; exit 1; }


        A further refinement, thanks to Stéphane's comment and answer here:



        $2 !~ /^[+-]?([[:digit:]]*.?[[:digit:]]*([eE][-+]?[[:digit:]]+)?|0[xX][[:xdigit:]]*.?[[:xdigit:]]*([pP][-+]?[[:digit:]]+)?)$/ { print "NAN: " $2; exit 1; }


        Broken out for slightly better legibility, that regex is:



        /^[+-]?([[:digit:]]*.?[[:digit:]]*([eE][-+]?[[:digit:]]+)?|
        0[xX][[:xdigit:]]*.?[[:xdigit:]]*([pP][-+]?[[:digit:]]+)?)$/


        ... where the intention is to allow a possible leading + or -, then either a floating point number or hexadecimal number. The floating point number has optional leading digits, an option separator (here fixed to be a period .), followed by some number of digits, optionally followed by an exponent. The hex number must start with 0x or 0X, followed by hex digits, a separator, more hex digits, and optionally followed by a "power" (exponent). The entire second field must match one of those formats (as anchored by ^ and $). Omitted here, for the purposes of this question, are the NAN and INFINITY options.



        Another option would be to force a numeric conversion, then compare it to zero and then further compare the original input to something that would convert to zero; more specifically, does it start with an optional + or -, then is it followed by zeros, or followed by a period and zeros:



        { number=0 + $2;
        if (!number && $2 !~ /^[+-]?(0+)|.0+/)
        print "NAN: "$2;
        }





        share|improve this answer





















        • 1





          You'd need to anchor the regexp (with ^), otherwise, it's just a test whether the second field contains a decimal digit. You'd also need to take care of numbers like .123. There's also whether you want to honour user's decimal radix (comma vs period). The last one would let strings like ., +, +.

          – Stéphane Chazelas
          Jan 16 at 21:49











        • Great points, Stéphane; thank you. I will correct the simpler aspects shortly.

          – Jeff Schaller
          Jan 17 at 0:43











        • notice that when converting strings to numbers awk will ignore any trailing junk (see my answer) and /^[+-]?0*.?0*$/ is far from being a thorough pattern matching strings that will be completely parsed to 0 by strtod (what about 0e13, .0e-0, 0x0, 0x.0p+13, etc?)

          – Uncle Billy
          Jan 17 at 1:58













        • Point well taken, @UncleBilly, as also noted by Stéphane above. I'm working on the "zero" regex right now...

          – Jeff Schaller
          Jan 17 at 2:00














        7












        7








        7







        A reasonable way to test would be to compare the field using tests similar to strtod, which is the method that awk uses to convert strings to numbers:



        $2 !~ / *[+-]?[[:digit:]]/ { print "NAN: " $2; exit 1; }


        The above differs from strtod in that it does not consider INFINITY or NAN to be "numbers". The leading space requirement could be relaxed under awk's default field-splitting behavior -- meaning the fields would never contain leading space:



        $2 !~ /[+-]?[[:digit:]]/ { print "NAN: " $2; exit 1; }


        A further refinement, thanks to Stéphane's comment and answer here:



        $2 !~ /^[+-]?([[:digit:]]*.?[[:digit:]]*([eE][-+]?[[:digit:]]+)?|0[xX][[:xdigit:]]*.?[[:xdigit:]]*([pP][-+]?[[:digit:]]+)?)$/ { print "NAN: " $2; exit 1; }


        Broken out for slightly better legibility, that regex is:



        /^[+-]?([[:digit:]]*.?[[:digit:]]*([eE][-+]?[[:digit:]]+)?|
        0[xX][[:xdigit:]]*.?[[:xdigit:]]*([pP][-+]?[[:digit:]]+)?)$/


        ... where the intention is to allow a possible leading + or -, then either a floating point number or hexadecimal number. The floating point number has optional leading digits, an option separator (here fixed to be a period .), followed by some number of digits, optionally followed by an exponent. The hex number must start with 0x or 0X, followed by hex digits, a separator, more hex digits, and optionally followed by a "power" (exponent). The entire second field must match one of those formats (as anchored by ^ and $). Omitted here, for the purposes of this question, are the NAN and INFINITY options.



        Another option would be to force a numeric conversion, then compare it to zero and then further compare the original input to something that would convert to zero; more specifically, does it start with an optional + or -, then is it followed by zeros, or followed by a period and zeros:



        { number=0 + $2;
        if (!number && $2 !~ /^[+-]?(0+)|.0+/)
        print "NAN: "$2;
        }





        share|improve this answer















        A reasonable way to test would be to compare the field using tests similar to strtod, which is the method that awk uses to convert strings to numbers:



        $2 !~ / *[+-]?[[:digit:]]/ { print "NAN: " $2; exit 1; }


        The above differs from strtod in that it does not consider INFINITY or NAN to be "numbers". The leading space requirement could be relaxed under awk's default field-splitting behavior -- meaning the fields would never contain leading space:



        $2 !~ /[+-]?[[:digit:]]/ { print "NAN: " $2; exit 1; }


        A further refinement, thanks to Stéphane's comment and answer here:



        $2 !~ /^[+-]?([[:digit:]]*.?[[:digit:]]*([eE][-+]?[[:digit:]]+)?|0[xX][[:xdigit:]]*.?[[:xdigit:]]*([pP][-+]?[[:digit:]]+)?)$/ { print "NAN: " $2; exit 1; }


        Broken out for slightly better legibility, that regex is:



        /^[+-]?([[:digit:]]*.?[[:digit:]]*([eE][-+]?[[:digit:]]+)?|
        0[xX][[:xdigit:]]*.?[[:xdigit:]]*([pP][-+]?[[:digit:]]+)?)$/


        ... where the intention is to allow a possible leading + or -, then either a floating point number or hexadecimal number. The floating point number has optional leading digits, an option separator (here fixed to be a period .), followed by some number of digits, optionally followed by an exponent. The hex number must start with 0x or 0X, followed by hex digits, a separator, more hex digits, and optionally followed by a "power" (exponent). The entire second field must match one of those formats (as anchored by ^ and $). Omitted here, for the purposes of this question, are the NAN and INFINITY options.



        Another option would be to force a numeric conversion, then compare it to zero and then further compare the original input to something that would convert to zero; more specifically, does it start with an optional + or -, then is it followed by zeros, or followed by a period and zeros:



        { number=0 + $2;
        if (!number && $2 !~ /^[+-]?(0+)|.0+/)
        print "NAN: "$2;
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jan 17 at 2:15

























        answered Jan 16 at 17:46









        Jeff SchallerJeff Schaller

        42k1156133




        42k1156133








        • 1





          You'd need to anchor the regexp (with ^), otherwise, it's just a test whether the second field contains a decimal digit. You'd also need to take care of numbers like .123. There's also whether you want to honour user's decimal radix (comma vs period). The last one would let strings like ., +, +.

          – Stéphane Chazelas
          Jan 16 at 21:49











        • Great points, Stéphane; thank you. I will correct the simpler aspects shortly.

          – Jeff Schaller
          Jan 17 at 0:43











        • notice that when converting strings to numbers awk will ignore any trailing junk (see my answer) and /^[+-]?0*.?0*$/ is far from being a thorough pattern matching strings that will be completely parsed to 0 by strtod (what about 0e13, .0e-0, 0x0, 0x.0p+13, etc?)

          – Uncle Billy
          Jan 17 at 1:58













        • Point well taken, @UncleBilly, as also noted by Stéphane above. I'm working on the "zero" regex right now...

          – Jeff Schaller
          Jan 17 at 2:00














        • 1





          You'd need to anchor the regexp (with ^), otherwise, it's just a test whether the second field contains a decimal digit. You'd also need to take care of numbers like .123. There's also whether you want to honour user's decimal radix (comma vs period). The last one would let strings like ., +, +.

          – Stéphane Chazelas
          Jan 16 at 21:49











        • Great points, Stéphane; thank you. I will correct the simpler aspects shortly.

          – Jeff Schaller
          Jan 17 at 0:43











        • notice that when converting strings to numbers awk will ignore any trailing junk (see my answer) and /^[+-]?0*.?0*$/ is far from being a thorough pattern matching strings that will be completely parsed to 0 by strtod (what about 0e13, .0e-0, 0x0, 0x.0p+13, etc?)

          – Uncle Billy
          Jan 17 at 1:58













        • Point well taken, @UncleBilly, as also noted by Stéphane above. I'm working on the "zero" regex right now...

          – Jeff Schaller
          Jan 17 at 2:00








        1




        1





        You'd need to anchor the regexp (with ^), otherwise, it's just a test whether the second field contains a decimal digit. You'd also need to take care of numbers like .123. There's also whether you want to honour user's decimal radix (comma vs period). The last one would let strings like ., +, +.

        – Stéphane Chazelas
        Jan 16 at 21:49





        You'd need to anchor the regexp (with ^), otherwise, it's just a test whether the second field contains a decimal digit. You'd also need to take care of numbers like .123. There's also whether you want to honour user's decimal radix (comma vs period). The last one would let strings like ., +, +.

        – Stéphane Chazelas
        Jan 16 at 21:49













        Great points, Stéphane; thank you. I will correct the simpler aspects shortly.

        – Jeff Schaller
        Jan 17 at 0:43





        Great points, Stéphane; thank you. I will correct the simpler aspects shortly.

        – Jeff Schaller
        Jan 17 at 0:43













        notice that when converting strings to numbers awk will ignore any trailing junk (see my answer) and /^[+-]?0*.?0*$/ is far from being a thorough pattern matching strings that will be completely parsed to 0 by strtod (what about 0e13, .0e-0, 0x0, 0x.0p+13, etc?)

        – Uncle Billy
        Jan 17 at 1:58







        notice that when converting strings to numbers awk will ignore any trailing junk (see my answer) and /^[+-]?0*.?0*$/ is far from being a thorough pattern matching strings that will be completely parsed to 0 by strtod (what about 0e13, .0e-0, 0x0, 0x.0p+13, etc?)

        – Uncle Billy
        Jan 17 at 1:58















        Point well taken, @UncleBilly, as also noted by Stéphane above. I'm working on the "zero" regex right now...

        – Jeff Schaller
        Jan 17 at 2:00





        Point well taken, @UncleBilly, as also noted by Stéphane above. I'm working on the "zero" regex right now...

        – Jeff Schaller
        Jan 17 at 2:00













        5














        I ended up with this:



        awk -v col=$col '
        typeof($col) != "strnum" {
        print "Error on line " NR ": " $col " is not numeric"
        noprint=1
        exit 1
        }
        {
        sum+=$col
        }
        END {
        if(!noprint)
        print sum
        }' $file


        This uses typeof, which is a GNU awk extension. typeof($col) returns 'strnum' if $col is a valid number, and 'string' or 'unassigned' if it is not.



        See Can I determine type of an awk variable?






        share|improve this answer




























          5














          I ended up with this:



          awk -v col=$col '
          typeof($col) != "strnum" {
          print "Error on line " NR ": " $col " is not numeric"
          noprint=1
          exit 1
          }
          {
          sum+=$col
          }
          END {
          if(!noprint)
          print sum
          }' $file


          This uses typeof, which is a GNU awk extension. typeof($col) returns 'strnum' if $col is a valid number, and 'string' or 'unassigned' if it is not.



          See Can I determine type of an awk variable?






          share|improve this answer


























            5












            5








            5







            I ended up with this:



            awk -v col=$col '
            typeof($col) != "strnum" {
            print "Error on line " NR ": " $col " is not numeric"
            noprint=1
            exit 1
            }
            {
            sum+=$col
            }
            END {
            if(!noprint)
            print sum
            }' $file


            This uses typeof, which is a GNU awk extension. typeof($col) returns 'strnum' if $col is a valid number, and 'string' or 'unassigned' if it is not.



            See Can I determine type of an awk variable?






            share|improve this answer













            I ended up with this:



            awk -v col=$col '
            typeof($col) != "strnum" {
            print "Error on line " NR ": " $col " is not numeric"
            noprint=1
            exit 1
            }
            {
            sum+=$col
            }
            END {
            if(!noprint)
            print sum
            }' $file


            This uses typeof, which is a GNU awk extension. typeof($col) returns 'strnum' if $col is a valid number, and 'string' or 'unassigned' if it is not.



            See Can I determine type of an awk variable?







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jan 16 at 17:51









            Nick ODellNick ODell

            1,0912920




            1,0912920























                2














                awk -v col=2 '
                $col+0==0 && $col!~/^[+-]?0/ { print "bad number " $col > "/dev/stderr" }
                {sum+=$col}
                END{print sum}' input-file


                It's up to you to complicate it if you want it to also handle .0 or .0e+33 as valid representations of 0; notice that awk will ignore trailing junk when converting strings to numbers ("1.4e1e3"+0, "1.4e1.e7"+0 or "14+13"+0 will be all equal to 14).






                share|improve this answer




























                  2














                  awk -v col=2 '
                  $col+0==0 && $col!~/^[+-]?0/ { print "bad number " $col > "/dev/stderr" }
                  {sum+=$col}
                  END{print sum}' input-file


                  It's up to you to complicate it if you want it to also handle .0 or .0e+33 as valid representations of 0; notice that awk will ignore trailing junk when converting strings to numbers ("1.4e1e3"+0, "1.4e1.e7"+0 or "14+13"+0 will be all equal to 14).






                  share|improve this answer


























                    2












                    2








                    2







                    awk -v col=2 '
                    $col+0==0 && $col!~/^[+-]?0/ { print "bad number " $col > "/dev/stderr" }
                    {sum+=$col}
                    END{print sum}' input-file


                    It's up to you to complicate it if you want it to also handle .0 or .0e+33 as valid representations of 0; notice that awk will ignore trailing junk when converting strings to numbers ("1.4e1e3"+0, "1.4e1.e7"+0 or "14+13"+0 will be all equal to 14).






                    share|improve this answer













                    awk -v col=2 '
                    $col+0==0 && $col!~/^[+-]?0/ { print "bad number " $col > "/dev/stderr" }
                    {sum+=$col}
                    END{print sum}' input-file


                    It's up to you to complicate it if you want it to also handle .0 or .0e+33 as valid representations of 0; notice that awk will ignore trailing junk when converting strings to numbers ("1.4e1e3"+0, "1.4e1.e7"+0 or "14+13"+0 will be all equal to 14).







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jan 17 at 1:53









                    Uncle BillyUncle Billy

                    5925




                    5925























                        1















                        If you give it a file that doesn't have numeric data,




                        $col ~ /[^-.[:digit:]]/ {print "Error, non-numeric :"; print $col; exit 1};


                        Explanation just use a RegEx to check for the presence of characters which are not digits nor floating point, sign, etc.




                        (or if one number is missing)




                        add



                        || ($col == "")


                        or



                        || (length($col) == 0)


                        to the rule.



                        Or you could use a comparison to NF if it's the last column like in your example.






                        share|improve this answer




























                          1















                          If you give it a file that doesn't have numeric data,




                          $col ~ /[^-.[:digit:]]/ {print "Error, non-numeric :"; print $col; exit 1};


                          Explanation just use a RegEx to check for the presence of characters which are not digits nor floating point, sign, etc.




                          (or if one number is missing)




                          add



                          || ($col == "")


                          or



                          || (length($col) == 0)


                          to the rule.



                          Or you could use a comparison to NF if it's the last column like in your example.






                          share|improve this answer


























                            1












                            1








                            1








                            If you give it a file that doesn't have numeric data,




                            $col ~ /[^-.[:digit:]]/ {print "Error, non-numeric :"; print $col; exit 1};


                            Explanation just use a RegEx to check for the presence of characters which are not digits nor floating point, sign, etc.




                            (or if one number is missing)




                            add



                            || ($col == "")


                            or



                            || (length($col) == 0)


                            to the rule.



                            Or you could use a comparison to NF if it's the last column like in your example.






                            share|improve this answer














                            If you give it a file that doesn't have numeric data,




                            $col ~ /[^-.[:digit:]]/ {print "Error, non-numeric :"; print $col; exit 1};


                            Explanation just use a RegEx to check for the presence of characters which are not digits nor floating point, sign, etc.




                            (or if one number is missing)




                            add



                            || ($col == "")


                            or



                            || (length($col) == 0)


                            to the rule.



                            Or you could use a comparison to NF if it's the last column like in your example.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 16 at 17:41









                            DrYakDrYak

                            1915




                            1915






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Unix & Linux Stack Exchange!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f494889%2fmake-awk-produce-error-on-non-numeric%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Can a sorcerer learn a 5th-level spell early by creating spell slots using the Font of Magic feature?

                                Does disintegrating a polymorphed enemy still kill it after the 2018 errata?

                                A Topological Invariant for $pi_3(U(n))$