User Tools

Site Tools


add_numbers_on_the_command_line

add numbers on the command line

Q. Add a bunch of numbers on the command line

A. You can do it in many ways.

Approach 1: Use python

| python -c "import sys; print(sum(int(line) for line in sys.stdin))"

For example

 % seq 1 10 | python -c "import sys; print(sum(int(line) for line in sys.stdin))"
55

Approach 2: Use unix-only tools

| paste -s -d + - | bc

For example

 % seq 1 10 | paste -s -d + - | bc               
55

Output of intermediate steps:

 % seq 1 10                     
1
2
3
4
5
6
7
8
9
10

 % seq 1 10 | paste -s -d +
1+2+3+4+5+6+7+8+9+10

 % seq 1 10 | paste -s -d + | bc
55

Ref:-

tags | add a bunch of numbers on command line pipe

add_numbers_on_the_command_line.txt · Last modified: 2020/10/26 17:15 by admin