How to summarize numbers from stdout with python

Let’s suppose that you want execute a command and get all integer numbers one per line and make a summary using python.

$ echo -e '1\n2\n3\n4\n5' | \
python -c "import sys; print sum(int(l) for l in sys.stdin)"

If you are using float numbers, just change ‘sum(int(l)’ to ‘sum(float(l)’ like following example.

$ echo -e '1\n2\n3\n4\n5' | \
python -c "import sys; print sum(float(l) for l in sys.stdin)"
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

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