sum total by column

Hi, i have a file which content the following:

>cat cols
data a:23:data
data b:76:data
data c:-30:data

i would like to sum up the value of column 2, but the result that return to me is 0. Can anyone help?

i'm using this code to do the sum

awk -F" " 'BEGIN {x=0} {x+=$2} END {print x}' cols

Your field separator is ":", so use -F: .

P.S. You don't need BEGIN {x=0},
Awk does that by default.

Try the following:

BEGIN {
     FS = "[ :]"
     x  = 0
}
{  x += $3  }
END {
     print "Total: " x
}

Hi, i try to use the code that given.. but it gave me a syntax error:

awk: line 1: syntax error at or near =

is this the correct way to use this code?

awk -F" " 'BEGIN {FS = "[ :]"x  = 0}{  x += $2  }END {print "Total: " x}'cols

Your field separator syntax is wrong. You have two field separators to handle - ' ' and ':', hence FS is set to the regular expression " [ :]"

Suggest you simply save code to a file, say cols.awk and invoke as follows:

awk -f cols.awk cols

I tested code using gawk on Vista SUA and it appears to work.

awk -F":" '{x += $2} END {print "Sum: "x}' cols
Sum: 69