0

Hope everyone is having a nice day. I'm new to Bash and I was playing around with a code that I came up with. What it does it takes the data in a CSV file(A simple marks sheet) and add up all the marks for each module in the csv file. The code goes like this,

count=-1
sum=0

while read module mark
do
    if(($count>-1))
    then
            echo "Mark is $mark"
            sum=$(( $sum + $mark ))
    fi
    count=$((count+1))
done < $1

echo $sum 

The CSV file is like this

Module,Mark
A,10
B,20
c,30
D,40
E,50

So I'm expecting to get the sum of the marks 150 but it gives me this error and stops executing.

Mark is 10
")syntax error: invalid arithmetic operator (error token is "

Can someone please help me out. Any help is much appreciated.

CodeLover
  • 21
  • 1
  • One-liner: `tail -n +2 input.csv | cut -d ',' -f 2 | paste -sd '+' | bc` – SergA Apr 08 '22 at 07:06
  • @SergA `awk` is probably more suited to do this instead of using multiple pipes – Aserre Apr 08 '22 at 08:53
  • @SergA Can you please explain a little bit more I just started about 3 days ago I don't get what your solution says. If it is not a bother can you give me some documentation links to look up. Thanks – CodeLover Apr 08 '22 at 09:13
  • @Aserre I'll look up on this as well Thank you – CodeLover Apr 08 '22 at 09:14
  • @CodeLover, explanations: • `tail` - print all lines of input file (`input.csv`) started from second line (`-n +2` flag); • `cut` - split each line by the comma symbol (`-d ','` flag) and print only second column (`-f 2` flag); • `paste` - concatenate/join all lines with `+` separator. In result this utility print one line with formula `10+20+30+40+50`; • `bc` - calculate result for formula. – SergA Apr 08 '22 at 09:40
  • For the awk solution : `awk -F "," '{if (NR!=1){result+=$2}} END{print "Mark is " result}' input.csv`. However, explaining an awk script is a bit tricky if you are not familiar with the tool. You can find [tutorials](https://www.google.com/search?q=awk+beginner+tutorial) online though – Aserre Apr 08 '22 at 09:58

0 Answers0