开发者

invalid sum expression while trying to obtain sum of index

开发者 https://www.devze.com 2023-03-07 13:36 出处:网络
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 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
0

精彩评论

暂无评论...
验证码 换一张
取 消