Summing Values ​​in a Single Line Comma Separated File

EDIT: Thank you all. Python solution worked lightning fast :)

I have a file that looks like this:

132,658,165,3216,8,798,651

but MUCH is larger (~ 600 kB). There are no new lines except one at the end of the file.

And now I have to summarize all the values ​​that are. I expect the final result to be quite large, but if I summarized it in C ++, I have a bigmoon library, so this should not be a problem.

How do I do this, and in which language / program? C ++, Python, Bash?

+3
source share
8 answers

Python

sum(map(int,open('file.dat').readline().split(',')))
+4
source

, "Awk"

sed -e 's/,/\n/g' tmp.txt | awk 'BEGIN {total=0} {total += $1} END {print total}'

  • - tmp.txt( )
  • Awk ,
+6

, bignum. :

str = ""
sum = 0
while input
    get character from input
    if character is not ','
        append character to back of str
    else
        convert str to number
        add number to sum
        str = ""
output sum
+1

(2 ** 64)/600000 ( - 14 ), 8 " " C. , .

+1

, . , . #, .

, (, 32-), , . -31 dword .

, double. .

0

python .

-1
source
tr "," "\n" < file | any old script for summing

Ruby is convenient because it automatically processes large numbers. I can’t remember that Awk does arbitrary arithmetic precision, but if so, you can use

awk 'BEGIN {RS="," ; sum = 0 }
     {sum += $1 }
     END { print sum }' < file
-1
source

Source: https://habr.com/ru/post/1704154/


All Articles