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
 
3 Comments

Posted by on May 28, 2013 in awk, Linux

 

Tags: , , , , ,

3 responses 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!

     
  2. Denis Akulov

    October 22, 2014 at 19:28

    Should it be `cat numbers.txt | paste -sd+ – | bc` ?

     
    • Emre Sevinç

      October 22, 2014 at 19:40

      Hello Denis,

      Both of them are valid. According to the man page: “With no FILE, or when FILE is -, read standard input.”

       

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 61 other followers

%d bloggers like this: