简体   繁体   中英

bash awk extract and sum values from one numeric col

I have some data in a file:

$ cat data.txt
facture-2817806.txt Total TTC 27.11 €
facture-2857125.txt Total TTC 37.92 €
facture-2895824.txt Total TTC 43.61 €
facture-2922275.txt Total TTC 46.73 €
facture-2935969.txt Total TTC  8.29 €
facture-2977623.txt Total TTC 41.79 €
facture-3005553.txt Total TTC 46.18 €
facture-3020047.txt Total TTC 20.34 €
facture-3061124.txt Total TTC 28.22 €
facture-3097529.txt Total TTC 59.65 €
facture-3258989.txt Total TTC 29.31 €
facture-3637195.txt Total TTC 11.17 €
facture-3681794.txt Total TTC 44.52 €
facture-3726992.txt Total TTC 28.20 €
facture-3752273.txt Total TTC 42.15 €
facture-3770970.txt Total TTC 24.01 €

I want to sum float value of one col, I extract the column:

$ cat data.txt | awk '{print $4}'
27.11
37.92
43.61
46.73
8.29
41.79
46.18
20.34
28.22
59.65
29.31
11.17
44.52
28.20
42.15
24.01
$

What is a good bash way to get the sum of that with one more pipe '|' ?

$ cat data.txt | awk '{print $4}' | xxx

Note: There a similar issue here: Why does AWK refuse to sum up floats but in my file float numbers are not alone. I look for just an additional liner after the pipe.

I want to sum float value of one col

The idiomatic way

awk '{count+=$4}END{printf "Total : %f\n",count}' your_file

The hard way

awk 'BEGIN{count=0}{count+=$4}END{printf "Total : %f\n",count}' your_file

As a side note, if you wish to specify the number of digits after the decimal point use something like %0.2f .

Note: You don't need a pipe at all.

Possible with awk , but in a different way:-

awk '{ sum += $4;printf "$%.2f\n",sum}' data.txt

it gives sum of $4 in a cumulative way

EDIT:- To get sum of all the values from column $4 in one shot:-

awk '{ sum += $4} END {printf "$%.2f\n",sum}' data.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM