I'm trying to extract the sum of numbers to a variable (cwr) in a file (wa_cidr) using this command:
cwr=$(grep -E "^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([0-9]|[1-2][0-9]|3[0-2]))?$" /tmp/wa_cidr | awk -F '/' '`{n += 2**(32 - $NF)}` END {print n}')
However, the output is empty.
If I change the part...
{n += 2**(32 - $NF)}
To...
{n += (32 - $NF)}
I get a valid result written to the cwr variable.
It would seem that I cannot do the power of (32 - $NF) using either 2**X or 2^X in AWK.
If I do it on the command line, e.g. using...
$ echo $(2**5)
There's no problem and the result is 32.
I have tried many variations on the formula (parantheses etc.) but nothing seems to Work.
What is wrong? Can it be done in another way?
Thanks, Søren
If your regexp is correct then this would be the correct syntax to do what you appear to be trying to do:
cwr=$(awk -F'/' '/^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([0-9]|[1-2][0-9]|3[0-2]))?$/{n += 2^(32 - $NF)} END {print n+0}' /tmp/wa_cidr)