Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Calculating Columns in AWK 2

Status
Not open for further replies.

rtrujill

MIS
Nov 16, 2004
6
US
When executing the following:

awk '{ SUM = SUM + $NF } END { print SUM }' test1.tx

I get:

1.05487e+06

How do I get the correct amount?
 
Take a look at the printf function:
printf "%d\n", SUM

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Another way is to set the output format variable:
Code:
BEGIN { OFMT ="%.0f" }
{ SUM += NF }
END { print SUM }
 
PHV & futurelet -

Thanks to both of you. You saved me from having to write a cobol program to calculate some fields.[afro]
 
I would lke to add to this question if I may.
I would like this awk to display total expenditures on salaries they are located in the second field. Then I would like it to display the total expenditures as a footer of the output. Here is my awk...

BEGIN {
print "\n\n\n Total Salary Expenditures \n--------------------\n"}
{ sum += $2 }
END { print "\n Total Salaries:" sum }


When I run awk -F":" salaries.awk employeeSalaries it prints the header and footer however the total=0

Originally I had {sum=sum +2} just as rtrujill, that didn't work either.
What in the world am I missing?

 
Perhaps the salary is not the 2nd field.
If it's the last field, use $NF.

Show a sample of your input data.
 
Oh sorry, I forgot to add that. Here is a sample:

John 24000 Customer Service
Mary 45020 Finance
Ted 33000 Human Resources
Jim 30500 Factory
Larry 32100 Shipping
Susan 34050 Accounting
Jack 15400 Delivery
Tim 50234 Management
Lee 34650 Accounting
Nick 23450 Shipping
 
Don't use [tt]-F":"[/tt]
The field-separator should be the default: whitespace.

If you need a different FS and if it's the same for all files you will process with program, it is best to set it within the program:
Code:
# Example only!! Don't use this on your file.
BEGIN { FS = ";"
  print "\n\n"
  print "Total Salary Expenditures"
  print "--------------------\n"}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top