Summing all fields in a file

I was playing around to see how stuff works, and was trying to sum all fields in a file.

cat file
1 2 3 4
5 6 7 8
9 10 11 12

I made this script:

awk 'BEGIN {OFS=RS}{$1=$1}{s+=$0} END {print "sum="s}' file

This gives 15 , why not 78 ?

I test it like this

awk 'BEGIN {OFS=RS}{$1=$1}{s+=$0;print $0} END {print "sum="s}'
1
2
3
4
5
6
7
8
9
10
11
12
sum=15

It only sums up column #1 , even when print $0 shows all number, why?

Edit: I know this works, but I was thinking of skipping the internal loop

awk '{for (i=1; i<=NF; i++) s=s+$i}; END{print s}'

As far as I know changing the OFS (Output Field Separator) to RS (Input Record Separator, a newline by default) and rebuilding will only alter the way awk print the records.

It will not make any difference in the original record which awk read and stored internally in its memory.

This is the reason why you get expected output while printing, but not while computing the sum.

further to Yoda, I think $0 would still contain as the original input record and performing maths would result on the integer part ( int($0) would return $1 ) in this case. (others please correct me here if this is not the case)

You have to play with RS

awk 'BEGIN {RS="[ \n]"} {s+=$0} END  {print s}' file

AFAIK, I guess multi-character RS is supported only by gnu awk ( though not very much sure).

the easiest is:

tr ' ' '\n' < myFile| awk '{s+=$0}END {print "sum="s}'
OR
echo `sed -e 's/$/+/;s/ /+/g' myFile` 0 | bc

This gets you a bit closer, but.... as noted above you'll have to play with RS/FS:

awk 'BEGIN {RS=FS}{$1=$1}{s+=$0} END {print "sum="s}' myFile

This gives sum=64 , so there are some missing to get to 78

I guess It's not woking because of taking field separater everytime instead when it is going to new Line. anybody correct me if i am wrong.