2

I have a list of integers, where each is on a separate line. I'm trying to find a quick way to sum them up directly in VIM without having to write a script that does it for me.

4

What worked for me was:

:%!awk '{print; total+=$1}END{print total}'
3

You can use this command:

com! -range=% Sum :echo eval(join(getline(<line1>,<line2>),'+'))

It basically gets the lines in the given range (by default whole file) as a list, and evaluates it by joining each list item with a + between each other.

1

Here's a fun (albeit slightly hacky) answer, although I believe it's the shortest answer you'll get:

:%norm Dj@"<C-v><C-a><cr>
p

(note that <C-v> means ctrl-v, and <C-a> means ctrl-a)

It works by doing the following on every line:

  • Deleting it (into the unnamed register)
  • Running the unnamed register as a count, and
  • Incrementing the next number by that much.

Then, on the last line, there isn't a next number to increment, so it breaks. However, we have the current sum in the unnamed register, so we can just paste it with p.

If you don't want a bunch of blank lines, you could modify the last line to V{p.

Unfortunately, this only works with positive integers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.