• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 223
  • Last Modified:

AWK totals

I am very new to awk, so I am hoping this should be relatively straightforward:
I have a text file with 4 columns and only 5 rows, and I am calling this little script when I want to display only two of the columns, and add two totals at the bottom. What I am trying is below, but the Total is coming out to 0, and the Average is writing 13100, which is just not correct (should be 50000ish)

The desired output is:
column1data     column4data
column1data     column4data
Total                  <sumofcolumn4>
Average         <sumofcolumn4/5>

I would like to know where I am going wrong and how to fix it.
Many thanks
{total = sum $4} 
{average = sum $4 / $5}
{printf"%-12s\t %-12s\n", $1, $4}
END { 
{printf "%-12s\t %-12d\n", "Total", total}
{printf "%-12s\t %-12d\n", "Average", average}

Open in new window

1 Solution
{printf"%-12s\t %-12s\n", $1, $4}
{total += $4}
{count += $5}

  printf "%-12s\t %-12d\n", "Total", total;
  printf "%-12s\t %-12f\n", "Average", total/count;
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Train for your Pen Testing Engineer Certification

Enroll today in this bundle of courses to gain experience in the logistics of pen testing, Linux fundamentals, vulnerability assessments, detecting live systems, and more! This series, valued at $3,000, is free for Premium members, Team Accounts, and Qualified Experts.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now