-1

The following data contains a variable number of fields per record with each row being a single record. Awk script that will add all of the fields for each row together and print the resulting sum per record.

rand.csv
1,3,5,8,10,11,54
1,2,3,4
15,18,21,42,37
1,1,1,0,0,3,16
4,1,8,0,4,6,13,16,17,20,8,6,4
13

This is what i wrote so far

BEGIN {

    FS=","

}

{
    sum = 0
    for(i=1; i<=NF; i++){
        sum+=$i;
    }
      print "Sum "$1""

    }

}

END{

    print "Sum of each row"
}
7
  • Are you using a shebang? Do you get an error? If so, what is the error?
    – mchid
    Feb 2, 2020 at 13:59
  • Im not using shebang, its just returning an output Feb 2, 2020 at 18:48
  • What does your error say?
    – mchid
    Feb 2, 2020 at 19:24
  • this is what i wrote....BEGIN{ } { { for(i=1;i<=NF;i++) {sum+=$i } print sum;sum=0 } what am i doing wrong because when i run awk -f random.awk random.csv im getting an error. Im required to add a begin block Feb 2, 2020 at 20:30
  • You don't need to rewrite the whole thing; just make like two changes to the original. One of those changes is that you need to remove the extra curly close bracket on line number 16. Then, make the other change and you should be good. i'll give you a hint: $1 usually refers to the first column in awk
    – mchid
    Feb 2, 2020 at 21:33

1 Answer 1

1
$ more rand.csv 
1,3,5,8,10,11,54
1,2,3,4
15,18,21,42,37
1,1,1,0,0,3,16
4,1,8,0,4,6,13,16,17,20,8,6,4
13

$ awk -F, '{for(i=1;i<=NF;i++)x+=$i;print x;x=0}' rand.csv 
92
10
133
22
107
13

Basically only thing I changed is the -F, at the front and use command line.

2
  • Could you please show this with the begin and end. I just want to ensure im placing this correctly. Feb 2, 2020 at 4:49
  • 1
    or just awk -F, '{for(i=2;i<=NF;i++)$1+=$i;print $1}' Feb 2, 2020 at 7:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .