Saturday, November 30, 2019

Re: Problems using :read with external command

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.





--
--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

---
You received this message because you are subscribed to the Google Groups "vim_use" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vim_use+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/vim_use/20191130201856.7fd5aad0%40bigbox.attlocal.net.

No comments:

Post a Comment