Reputation: 8119
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
Reputation: 4624
I need this enough that it needed to be easier.
Added the below to my .vimrc
and can now:
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).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
:call Sum()
Upvotes: 2
Reputation: 51663
I'd recomend to take a look at csv.vim source, it has a SumColumn
function IIRC in the ftplulgin.
Upvotes: 3