Reman
Reman

Reputation: 8119

Column totals in Vim

Does anyone know how to sum all colums in a table in Vim without using AWK or SED but vimscript?

I want to select the columns which I want to sum and have the value below

like this:

2,50       € 2,50
25         € 2.200,40
0,30       € 0,309
100        € 1.400,3
23,50      € 23,5
--------------------
Sum col1   Sum col2

This is an example with 2 columns, but I often have more columns.
The problem I had with awk is that it cannot handle the decimals seperator "," and thousand seperator "."

Upvotes: 4

Views: 3699

Answers (2)

Justin
Justin

Reputation: 4624

I need this enough that it needed to be easier.

Added the below to my .vimrc and can now:

  • Visually select the column
  • Yank it into the default register (y)
  • <Leader>s in normal mode—copies the summed result into the * register
    (* register may not be available with your vim build, but you could change it from let @* = ... to let @" = ..., or whatever register you want the result saved to).
  • paste the result p, in normal mode.
function Sum()
    let @* = system("awk '{total+=$1}END{print total}'", @")
endfunction

function Sub()
    let @* = system("awk '{total-=$1}END{print total}'", @")
endfunction

nnoremap <silent> <Leader>s :call Sum()<CR>
nnoremap <silent> <Leader>x :call Sub()<CR>

Update

You did mention a pure Vim way, and I gave you an awk way 😀

This also works, with a few more steps (surely some shortcuts could be added)

function Sum()
    let @a = substitute(trim(@"), "\<c-j>", "+", "g")                                                              
endfunction
  • Visually select the column
  • :call Sum()
  • Move to where you want the value
  • In insert mode: Cr=Cra ← (Ctrl+r = Ctrl+r a)

Upvotes: 2

Zsolt Botykai
Zsolt Botykai

Reputation: 51663

I'd recomend to take a look at csv.vim source, it has a SumColumn function IIRC in the ftplulgin.

Upvotes: 3

Related Questions