Find the answer to your Linux question:
Results 1 to 2 of 2
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    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?

  2. #2
    Linux Engineer drl's Avatar
    Join Date
    Apr 2006
    Saint Paul, MN, USA / CentOS, Debian, Slackware, {Free, Open, Net}BSD, Solaris

    awk 'BEGIN{p=1}{p *= $1}END{print "p for",NR,"lines = ",p}' input_file
    so for a file 1,2,3 on separate lines one obtains, say for the data on file z7
    p for 3 lines =  6
    The man page on awk can seem long, but is very useful for factual questions.

    Best wishes ... cheers, drl
    Welcome - get the most out of the forum by reading forum basics and guidelines: click here.
    90% of questions can be answered by using man pages, Quick Search, Advanced Search, Google search, Wikipedia.
    We look forward to helping you with the challenge of the other 10%.
    ( Mn, 2.6.n, AMD-64 3000+, ASUS A8V Deluxe, 1 GB, SATA + IDE, Matrox G400 AGP )

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts