On 2019-11-30 20:36, Cesar Romani wrote:
> I have a file, test.txt, containing two lines:
>
> 18415
> 480
>
> If I do:
> :%!gawk "{sum+=$1}END{print sum}"
> I get the result in a new buffer, but if I try to put the result
> below the last line, using
> r %!gawk "{sum+=$1}END{print sum}"
> I get:
> E484: Can't open file test.txt!gawk
If the file is on disk, you can read in the results of passing it
through awk:
:$r !gawk '{sum+=$1}END{print sum}' %
(note the single-quotes to ensure the "$1" gets passed properly to
awk).
Alternatively, you can pass the file (or a range of its lines)
through awk and have awk print the lines as well as the sum:
:%!awk '{i+=$1; print}END{print i}'
Or, you can do it all within vim:
:let @a=0 | g/^/let @a=@a+getline('.')
and then put the contents of register "a" at the end of your file. :-)
-tim
PS: Strangely I needed to do
let @a=@a+getline('.')
because
let @a+=getline('.')
failed with
E734: Wrong variable type for +=
A little unexpected given that the docs say
:let {var} += {expr1} Like ":let {var} = {var} + {expr1}".
but the latter form works where the former form doesn't.