I have a script which outputs some timing data a line at a time. There are approx. 10 lines echoed, each line looks something like this:
0.741 http://checkip.dyndns.org 94.170.119.226
Since I needed to add all the values in the first column, I piped the output to grep, matching and printing the first numerical column, then piped it on to tr to replace new lines with '+', then piped to sed to replace the final '+' with nothing, and finally to bc to add the values. Then bc gave me a stdin syntax error - damn it, maybe I'm not quite so clever as I thought I was.
On examining the code I discovered that if I left off the final pipe to bc I got what I thought I should have - that being:
$ getip test | grep -o "^[0-9.]*" | tr "\n\r\f" "+" | sed "s/\(.*\)+/\1/"
0.409+0.087+0.116+0.294+0.214+0.342+0.595+0.232+0.380+0.494 [Note: no new line, prompt is here as expected]
$ echo 0.409+0.087+0.116+0.294+0.214+0.342+0.595+0.232+0.380+0.494 | bc
3.163
So I copied and pasted those values into an echo statement, piped to bc, and it worked fine as shown above.
As another test I ran the command again, this time assigning the result to a variable, and then piped the variable to bc. That also worked fine, see code below (the top line has the error shown when piped to bc):
$ getip test | grep -o "^[0-9.]*" | tr "\n\r\f" "+" | sed "s/\(.*\)+/\1/" | bc
(standard_in) 1: syntax error
$ var1=$(getip test | grep -o "^[0-9.]*" | tr "\n\r\f" "+" | sed "s/\(.*\)+/\1/")
$ echo $var1
0.332+0.111+0.081+0.283+0.155+0.355+0.607+0.297+0.382+0.452+0.294
$ echo $var1 | bc
3.349
What I want to know is why I get the syntax error from bc when I run it as one line? Any ideas?
Many thanks.
PS. The somewhat simpler alternative works with no problems.
$ getip test | grep -o "^[0-9.]*" | awk '{sum+=$1} END {print sum}'
2.999