0

I have a multi-line of output from some shell scripts, one integer number per line. Like:

12
11
55
337
11
34

Problem is, how could I sum up these numbers with a shell command? I tried sum, but it doesn't do what is intended:

<some_shell_scripts> |sum
36373     2 

Any simple solution in ksh or bash?

Qiang Xu
  • 4,353
  • 8
  • 36
  • 45

4 Answers4

4

With awk you can make it with something like this line:

$ awk '{count+=$1} END{print count}' file
460

With bash:

sum=0
while read number
do
  sum=$(($sum + $number))
done < file
echo $sum

Test:

$ sum=0; while read number; do sum=$(($sum + $number)); done < file
$ echo $sum
460
fedorqui
  • 275,237
  • 103
  • 548
  • 598
3

Pipe that to awk:

<some_shell_scripts> | awk 'NF{sum+=$1} END {print sum}'
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

Use bc for command-line calculations, awk is overkill.

Eg:

echo "23 + 23 + 23" | bc
69
Pedantic
  • 5,032
  • 2
  • 24
  • 37
1

Replace all the '\n' with '+' by sed and then bc

<some_shell_scripts> | sed ':a;N;$!ba;s/\n/+/g' | bc
notbad
  • 2,797
  • 3
  • 23
  • 34
  • What does the first sed expression mean? – Qiang Xu Dec 06 '13 at 16:43
  • 1
    @QiangXu http://stackoverflow.com/questions/1251999/sed-how-can-i-replace-a-newline-n – notbad Dec 06 '13 at 16:44
  • Here is what I got: `sed: 0602-417 The label :a;N;$!ba;s/\n/+/g is greater than eight characters` – Qiang Xu Dec 06 '13 at 16:51
  • @QiangXu What's your input? It is okay here. I just copy the input ,and cat then sed then bc. – notbad Dec 06 '13 at 16:54
  • Still same error. Looks it is unrelated to the input, e.g, how many lines of integers, but it may be that my sed version is not the same as yours? `sed --version` doesn't work for me here. But it looks mine is not GNU `sed`. My `sed` comes with the AIX machine. – Qiang Xu Dec 06 '13 at 17:08
  • @QiangXu my sed it GNU sed version 4.2.1. you can also use other methods to replace '\n' by '+', for example tr. – notbad Dec 06 '13 at 17:10