Awk product of nth field

How do I do the product of nth filed just like sum. For sum I know like

awk '{ sum += $12 } END {printf "%.2f\n", sum}'

works as initial sum = 0.

But for product how do initialize the variable to 1?

This should work for most awk versions:

awk '{ p *= $1 } END{ print p }' p=1 input-file

For gnu awk, and other recent versions, an alternative:

awk -v p=1 '{ p *= $1 } END{ print p }'  input-file

---------- Post updated at 19:51 ---------- Previous update was at 19:51 ----------

Of course you can use printf() as you did in your example instead of print.

1 Like

This works for LinuxMint (i.e. Ubuntu, i.e. Debian, ...):

awk 'BEGIN{ p=1 } { p *= $1 } END{ print p }' input_filename

and personally I find it neater to read...