Using awk to sum a field in a file

25 pts.
Tags:
Unix
Unix administration
Unix commands
Unix OS
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: July 22, 2009  7:45 PM
UPDATED: August 4, 2009  8:07 PM

Answer Wiki

Thanks. We'll let you know when a new response is added.

<b><i>I think</i></b> you could use a conditional expression as in C.

Something like this:

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

In this example, if $5 is greater than 160 it will sum $3, otherwise it will sum $2.

Discuss This Question: 1  Reply

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when members answer or reply to this question.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
  • Gchahl
    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
    25 pointsBadges:
    report

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

To follow this tag...

There was an error processing your information. Please try again later.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Thanks! We'll email you when relevant content is added and updated.

Following