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?

有帮助吗?

解决方案 2

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

其他提示

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top