sneha sneha - 4 months ago 11
Linux Question

calculate sum of a particular column based on header in bash

I have a test.csv file as below and wanted to calculate the total sum of views column and print the total views values.

name, rank, views

rio, 1, 45

sid, 3,90

mark,5,32

tom,4,56

cathrine,2,51


Please let me know the relevant code. Thanks.

Answer
awk -F\, 'NR==1 {for(i=1;$i !~ /views/ ;i++);} {sum+=$i; print $0} END {print "sum: ",sum} ' test.in