RSS

GNU/Linux command line tip of the day: sum of numbers in a column

28 May

More often than not, I need to quickly need to see the sum of a column of numbers when I’m doing some processing on the GNU/Linux command line. For the sake of simplicity, let’s assume that you have the following output from some command line pipe:
$ cat numbers.txt
1
2
3
4
5
6
7
8
9
10

So far I was generally employing awk or xargs, but I’ve decided to explore a simpler way and this is what I have discovered:


$ cat numbers.txt | paste -sd+ | bc
55

or if you want a running total:


$ cat numbers.txt | sed 's/^/.+/' | bc
1
3
6
10
15
21
28
36
45
55

Of course it is possible to use Python, or simply invoke Perl to do a lot of fancy processing but I think as far as simplicity goes, those two solutions, especially the first one, is a nice addition to your Linux toolbox. Note that the first solution is really minimalist: the paste command is part of the GNU coreutils.

About these ads
 
1 Comment

Posted by on May 28, 2013 in awk, Linux

 

Tags: , , , , ,

One response to “GNU/Linux command line tip of the day: sum of numbers in a column

  1. nbiser

    June 5, 2013 at 01:31

    Great method!

     

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

 
Follow

Get every new post delivered to your Inbox.

Join 59 other followers

%d bloggers like this: