Do quick arithmetic on numbers from STDIN with any formatting using a perl one liner.

perl -ne '$sum += $_ for grep { /\d+/ } split /[^\d\-\.]+/; print "$sum\n"'
Good for summing the numbers embedded in text - a food journal entry for example with calories listed per food where you want the total calories. Use this to monitor and keep a total on anything that ouputs numbers.
Sample Output
echo "I had 10 goats, then sam brought 5 more. \
Then we bought 4 more goats and 2 goats had babies. \
How many goats did we have?" | \
perl -ne '$sum += $_ for grep { /\d+/ } split /[^\d\-\.]+/; print "$sum\n"'
21

perl -ne '$sum += $_ for grep { /\d+/ } split /[^\d\-\.]+/; print "$sum\n"'
1, '2' | 3, (-2) -.5
3.5

What Others Think

I needed the average so made a little tweak perl -ne '$cnt ++; $sum += $_ for grep { /\d+/ } split /[^\d\-\.]+/; print $sum/$cnt . "\n"'
mp3tricord · 651 weeks and 4 days ago
One of the most important aspects of coding for kids meaning. Unlike the computer language, the coding language for kids is more simple to understand. Its purpose is to write and communicate instructions to a computer. The programming language resembles English, but has several additional parameters and rules. This is especially helpful when a child does not know much about computers. The definition is easy to comprehend, but the basics of coding for kids meaning are still complicated.
illianna · 9 weeks and 1 day 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?

commandlinefu.com 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.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

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: