I came across that if we use awk 0 inputfile, it will not print anything cause 0 means false of the condition. If we use awk 1 inputfile, it will print everything as 1 means true for each line awk interpret.If we use awk any_string inputfile, it will not print anything because all awk variable initialized as zero thus false.But if we use awk any_integer inputfile, it will become true and print each line of the file, may I know what is the reason ?I can't find this has been explained in the GNU awk manual though.
awk condition of true and false
awk;gawk
True for awk is either a non-empty string or a non-zero number (with numbers being decimal integer or floating point and with some awk implementations hexadecimal or octal are supported as well). Things enclosed in double quotes are strings, unquoted literal numbers are numbers, but for anything else, there are complex rules to determine if something is to be treated as a string or a number. The GNU awk manual has a whole chapter on that.True:awk '1' (non-zero number)awk '1e8' (non-zero number)awk '-0.01' (non-zero number)awk 'foo' (non-empty string)awk '0' (non-empty string)awk '0 ' (concatenation yields a string which here is non empty)echo 0 | awk '$1 ' (same for a $n field)awk 'substr(000, 1, 1)' (result of substr() is always a string)echo '0foo' | awk '$0' ($0 is a non-numerical string so is considered as a string (non-empty))False:awk '0' (0 number)awk '' (empty string)echo 0000e123 | awk '$1' ($1 is considered a number if it's a numerical string which it is here and being 0)echo '  0  ' | awk '$0' (leading and trailing spaces are ignored to determine if a string is numerical).awk ' 2foo - 2' (a string involved in an arithmetic expression is converted to a number with anything past the number ignored)awk 'unset_or_empty_variable' (empty string)awk 'non-numerical-string + 0'YMMV:awk '1e-500' (some will complain, some will treat it as 0)awk '0x1 + 0' (not all awk implementations support hexadecimals, on those that do 0x1 is converted to 1, in others to 0. Some version of the POSIX specification inadvertently required implementations to support that hex number there and it's been retracted later. Still gawk does recognise that hex number when POSIXLY_CORRECT is in the environment)awk '010 - 8' (same (well not quite as the 010 is literal here as opposed to converted from a string) for octals)awk '0x1 - 1' (on awk implementations that don't support hex numbers, 0x1 is the concatenation of 0 and the x1 variable which yields 0 which is converted to a number (0), if you subtract 1 you get -1 which is non-zero number).What that means is that if you want to check if a string is non-empty, you should not do:awk '$1 {print $1, is not empty}'Butawk '$1 !=  {print $1, is not empty}'Otherwise it would not say 0 or -0000E+00001234 are non-empty.