Using awk to sum a field in a file
25 pts.
0
Q:
Using awk to sum a field in a file
I am using the following command to sum the 3rd column in a ~ delimited file.

awk -F~ '{total+=$3} END{print total}' /tmp/foo

Can I add conditions to this command e.g. sum column 3 if column 5 greater than 160 and less than 171 etc?

Thanks
ASKED: Jul 22 2009  7:45 PM GMT
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
0
270 pts.
0
A:
 RATE THIS ANSWER
0
Click to Vote:
  •   0
  •  0
  • AddThis Social Bookmark Button
I think you could use a conditional expression as in C.

Something like this:

awk -F~ '{total += $5 > 160 ? $3 : $2} END{print total}' /tmp/foo


In this example, if $5 is greater than 160 it will sum $3, otherwise it will sum $2.
Last Answered: Jul 29 2009  9:29 PM GMT by Mr786976   270 pts.
Latest Contributors: Carlosdl   29855 pts.
0
0
Discuss This Answer:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _



_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

Gchahl   25 pts.  |   Aug 4 2009  8:07PM GMT

Thanks guys. I have tried this but does not work for me. I keep getting:

awk: syntax error near line 1
awk: illegal statement near line 1
awk: illegal statement near line 1

I have tried to change a few things here and there but no go.

Cheers

 
0