0

I'm processing some data using bash. I'm checking whether the data is complete by summing up the first column. It should consist of 0 - 500 with 0.1 increment. Unfortunately, the actual numbers are slightly off so that the sum can equal 1250653.9 instead of 1250250.0 . This could be avoided if I rounded each number before summing. Currently, I use the following:

cat L_z_expectation.dat | awk '{ print $1 }' | paste -sd+ | bc

Is there a way of pasting "+0.0001" to each row, then individually piping each row to bc in a single line?

Samveen
  • 3,482
  • 35
  • 52
Mr.Weathers
  • 398
  • 1
  • 5
  • 19
  • A minor aside: You dont need the `cat` command. You could just pass the filename as the second paramter to `awk`. See [this page](http://mywiki.wooledge.org/BashPitfalls) – Samveen Aug 08 '13 at 09:25

2 Answers2

2

Most implementations of awk seem to use double-precision floating numbers, so it can be enough for what you want.

So you can use only awk for what you want:

awk 'BEGIN {s=0;} {s+=$1} END {print s}' L_z_expectation.dat

You may need to use printf instead print to display numbers with enough precision.

If you still want to round the first column, you can then do the following:

awk 'BEGIN {s=0;} {s+=int($1+0.5)} END {print s}' L_z_expectation.dat
Bentoy13
  • 4,886
  • 1
  • 20
  • 33
0

Just appending it awk would be fine I think.

cat L_z_expectation.dat | awk '{ print $1 "+0.0001"}' | paste -sd+ | bc

Or do you need to omit paste instead?

cat L_z_expectation.dat | awk '{ print $1 "+0.0001"}' | bc
konsolebox
  • 72,135
  • 12
  • 99
  • 105
  • Ahh of course. Thats a great idea. It works well, but when I try to set the scale it doesnt work. the first bc still returns the numbers to their full precision . `cat L_z_expectation.dat | awk '{print "scale=1;"$1"+0.0000000001"'} | bc | paste -sd+ | bc` – Mr.Weathers Aug 08 '13 at 10:10
  • Forgot that bc wont set a scale with addition. I fixed it by dividing by 1.0 – Mr.Weathers Aug 08 '13 at 10:16