Compute the numeric sum of a file

sed i"+" file.txt | xargs echo 0 |bc
In the file data.txt there is a single column of numbers. Sed adds a "+" between lines and xargs prepares the output for bc. The "echo 0" is to avoid to have a "+" at the beginning of the line.
Sample Output

2011-02-09 10:14:22

What Others Think

Hmm... interesting, but we can do better. First let's get rid of xargs: echo 0 $(sed i+ file.txt) | bc Next, use the right tools for the job: paste -sd+ < file.txt | bc paste (join together) -s (serial, in one line) -d+ (delimited with +)
flatcap · 525 weeks and 5 days ago
Thanks flatcap! Those are much better, xargs even fails for big files. Huge difference, the second one is the best: [email protected]:~$ seq 1000000 > file.txt [email protected]:~$ time echo 0 $(sed i+ file.txt) | bc 500000500000 real 0m5.064s user 0m5.150s sys 0m0.260s [email protected]:~$ time paste -sd+ < file.txt | bc 500000500000 real 0m0.851s user 0m0.820s sys 0m0.040s Cooool.... Cheers.
rubenmoran · 525 weeks and 5 days ago
jp · 524 weeks and 3 days ago
So many ways to do it. The one with paste -s is the best. Here's another rather silly one: sed i"+" file.txt | tr '\n' ' ' | sed 's/^/0 /' | sed 's/$/\n/' | bc
jp · 524 weeks and 3 days ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this? is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands

Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.


Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: