Using awk to sum all entries in one column

Had to search this one for a while… here is the source file:

360109368 15004557 java.lang.String
310090432 7692644 char[]
179389488 7474562 java.util.HashMap$Entry
71350968 70689 java.util.HashMap$Entry[]
14298360 109019 * ConstMethodKlass
7853616 109019 * MethodKlass
7409816 119136 java.lang.Object[]
7302080 17556 int[]
7094864 11288 byte[]
I wanted the sum of all the numbers in the first column and heres the awk line I used:
cat sourcefile | awk ‘{print $1}’ | awk ‘BEGIN{sum=0}{sum+=$1}END{print “Total: ” sum}’
Advertisements

2 responses to this post.

  1. Posted by Lonnie Holcomb on August 17, 2013 at 4:13 PM

    how do I pick which lines to specifically add together in the column?

    Reply

    • Posted by Freddy on August 19, 2013 at 11:04 AM

      cat file | : this one prints entire file to the pipe
      awk ‘{print $1}’ : this is where you pick which column you want $1 is the first $2 is the second.. Separated by a space
      awk ‘BEGIN…. : this is the magic -> {sum+=$1} it says add all column $1 to sum and there is only 1 column at this point.

      Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: