when I want to check if a returned value is integer or not I use this in bash script:
if [ -z "$value" ]
then
echo 0
else
echo $value
fi
I was trying to use z option in awk with if. for example i have this line:
PRIMARY SECONDARY CONNECTED 350 800
I tried using this:
/bin/awk '{if( -z $1){print "0"}else{print $1}}' script
no matter i replace $1 with $2 or $3 or $4 or $5 it always return 0. am I using awk in a wrong way?
($1+0 || $1~/^0/)doing? – BlackCrystal Feb 05 '19 at 09:34$1+0checks if the numeric value of$1is non-zero (which will be if$1is already a non-zero number or is a string which starts with a non-zero number), and$1~/^0/checks if it's the number 0 or a string starting with0(not"foo", or"", which will also evaluate to 0 when converted to a number) – Feb 05 '19 at 09:44$1~/^[0-9]/. For numbers in general, you'll have to implement the whole ofstrtod()in slow awk if you don't like my hack. – Feb 05 '19 at 09:50awkis to test$1+0 == $1, that is to force the value to a number and see if it compares equal to the original. (Strings get turned to0in the process, and that doesn't compare equal to the original string.) This accepts anythingawkthinks is a number, like123.34e5, or-0. – ilkkachu Feb 05 '19 at 10:10echo | awk '{$1="123.34e5"; print $1, $1+0, $1+0 == $1}'. You shouldn't try with fields, becauseawknot only splits a line withIFS, it also turns into numbers the fields which look like numbers (pass the strtod-test).echo 0 | awk '{print $1 ? "yes" : "no"; $1="0"; print $1 ? "yes" : "no"}'– Feb 05 '19 at 14:43echo 123.34e5 | awk '{ print $1, $1+0, $1+0 == $1 }'. But perhaps you're right, perhaps it does some autodetecting. – ilkkachu Feb 05 '19 at 17:16==will do a numeric comparison, etc. -- anyways, my point stands: your trick is not reliable. – Feb 05 '19 at 17:41