How to run sum of a buffer?

165 views Asked by At

So, from my log file, I processed some string and finally got this result in, let's say buffer name "1"

12
23
34
45

How can I get a sum of a given buffer?

(defun sum-of-buffer (buf)
  (interactive "bBuffer Name: ")
   ....
  (message "%i" sum))

Or is there a convenient function combination?

2

There are 2 answers

0
lawlist On

How about using calc -- select the region in the shape of a rectangle -- and type: C-u C-x * :

Alternatively, how about?:

(let ((sum 0))
  (save-excursion
    (goto-char (point-min))
    (while (re-search-forward "[0-9]*\\.?[0-9]+" nil t)
      (setq sum (+ sum (string-to-number (match-string 0))))))
  sum)
0
gsg On

If you're on a Unix machine, C-x h M-| and then awk '{s+=$1} END {print s}'.