How to sum all numbers in the form of scientific notation in bash

Viewed 129

I have a data file like this

  1.59949146E+01  1.59949146E+01  1.59949146E+01  1.59949146E+01  1.59949146E+01
  1.59949146E+01  1.59949146E+01  1.59949146E+01  1.59949146E+01  1.59949146E+01
  1.59949146E+01  1.59949146E+01  2.39850450E+01  2.39850450E+01  2.39850450E+01
  2.39850450E+01  2.39850450E+01  2.39850450E+01  2.39850450E+01  2.39850450E+01
  2.39850450E+01  2.39850450E+01  2.39850450E+01  2.39850450E+01

To sum all the numbers, I use the following code

awk '{ for(i=1;i<=NF;i++){ print $i}}' number.txt |awk '{printf ("%f ", $0)}' |awk '{ for(i=1;i<=NF;i++){ print $i}}'|paste -sd+  | bc

First, it changes all raws to a single column

awk '{ for(i=1;i<=NF;i++){ print $i}}' number.txt 

1.59949146E+01
1.59949146E+01
1.59949146E+01
1.59949146E+01
1.59949146E+01
1.59949146E+01
1.59949146E+01
1.59949146E+01
1.59949146E+01
1.59949146E+01
1.59949146E+01
1.59949146E+01
2.39850450E+01
2.39850450E+01
2.39850450E+01
2.39850450E+01
2.39850450E+01
2.39850450E+01
2.39850450E+01
2.39850450E+01
2.39850450E+01
2.39850450E+01
2.39850450E+01
2.39850450E+01

Using awk '{printf ("%f ", $0)}' I will have the following output

15.994915 15.994915 15.994915 15.994915 15.994915 15.994915 15.994915 15.994915 15.994915 15.994915 15.994915 15.994915 23.985045 23.985045 23.985045 23.985045 23.985045 23.985045 23.985045 23.985045 23.985045 23.985045 23.985045 23.985045

Again I need to use awk '{ for(i=1;i<=NF;i++){ print $i}}' to convert raws to a column and then using paste -sd+ | bc I can have the answer

479.759520

Although it works I'm looking for a better way to reduce the steps.

1 Answers

You can use this single awk for this:

awk '{for (i=1; i<=NF; ++i) sum += $i} END {print sum}' number.txt

479.76

or using printf:

awk '{for (i=1; i<=NF; ++i) sum += $i} END {printf "%f\n", sum}' number.txt

479.759515

If you have gnu awk then use:

awk -v RS='[[:space:]]+' '{sum += $1} END {print sum}' number.txt
Related