Problems using :read with external command

9 views
Skip to first unread message

Cesar Romani

unread,
Nov 30, 2019, 8:37:07 PM11/30/19
to vim...@googlegroups.com
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

How can I put the result of an external command below the last line?
Many thanks in advance,

--
Cesar

Tim Chase

unread,
Nov 30, 2019, 9:19:06 PM11/30/19
to Cesar Romani, vim...@googlegroups.com
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.





Reply all
Reply to author
Forward
0 new messages