常常會遇到一個檔案內容都是數字, 一個數字一行, 要加總, 然後要算出平均值, 要怎麼做呢?
檔案 count.txt
- vim count.txt
1.1
2.3
3
4
5.5
計算加總
- $ cat count.txt | awk '{sum+=$1} END {print "Sum = ", sum}'
Sum = 15.9
計算平均值
- $ cat count.txt | awk '{sum+=$1} END {print "Average = ", sum/NR}'
Average = 3.18
If you are just want to sum the number, much easy to use bc command
http://www.linuxask.com/questions/how-to-sum-a-file-of-numbers
paste -sd+ num.txt | bc
55
thanks. 🙂