i need to take the sum of all the values present at a particular index in every line of a csv file. the file 开发者_StackOverflowmay contain more than 50000 records. so efficiency is a given.
i was trying the following code. but doesnt seem to be working.
#!/bin/sh
FILE=$1
# read $FILE using the file descriptors
exec 3<&0
exec 0<$FILE
while read line
do
valindex=`cut -d "," -f 3`
echo $valindex
sum=`expr $sum+$valindex`
done
echo $sum
You should initialise sum before your while loop:
sum=0
You need to cut the line you are reading:
valindex=`echo $line|cut -d "," -f 3`
You need a space before and after the plus in expr:
sum=`expr $sum + $valindex`
Alternatively, use awk. It's a lot simpler:
awk -F, '{SUM+=$3} END{print SUM}' $FILE
Or one of my favourite patterns:
cut -d "," -f 3 "$FILE" | paste -sd+ | bc
精彩评论