What is the difference in this two awk command?

What is the difference in these two awk command? Both returns same output but I am not sure what is the use of +0 in command 1.


awk -F "," '{print $1+0,$2+0,$3+0}'

awk -F "," '{print $1, $2, $3}'

The first one turns ("casts") the "strings" into numbers.

If the output's the same on both, it's probably because the input is already numerical.

$ echo a b c | awk '{ print $1, $2, $3 }'
a b c
$ echo a b c | awk '{ print $1+0, $2, $3 }'
0 b c
$ echo a b c | awk '{ print $1+0, $2+0, $3 }'
0 0 c
$ echo a b 27 | awk '{ print $1+0, $2+0, $3 }'
0 0 27
$ echo a b 27 | awk '{ print $1+0, $2+0, $3+0 }'
0 0 27
$ echo a b 27 | awk '{ print $1+0, $2+0, $3+1 }'
0 0 28
$
1 Like

Wonderful !!! Thanks for examples.

Hello Scott/later_troy,

Adding one more small example here too. In awk , strings could be converted to numbers and numbers could be converted to strings, if the context of the awk program demands it. For example, If numeric values appear in string concatenation, they are converted to strings. Consider the following:

two = 2; three = 3
print (two three) + 4

awk 'BEGIN{two=2;three=3;print (two three)+4}'
27   ###Output

This prints the (numeric) value 27 . The numeric values of the variables two and three are converted to strings and concatenated together. The resulting string is converted back to the number 23, to which 4 is then added. Also while taking 5th field of df in BASH means to have the used file system percentage could be one more example for this too.

Thanks,
R. Singh