Sunday, June 20, 2010

Re: search for output of shell command

On 06/20/2010 06:38 AM, Yosi Izaq wrote:
> For example, search for line starting with current day (^17).
> How can it be done?- The following doesn't work: /^r!date | awk
> '{print $3}'

For your particular use-case, I'd use vim's internal strftime()
function:

:nnoremap <f4> /^<c-r>=strftime('%d')<cr><bslash>><cr>
:cnoremap <f4> <c-r>=strftime('%d')<cr>

You don't mention what single-digit dates look like in your file
(whether they are left-justified, or padded with spaces or a
leading zero). So you might have to use "%e" (pad with spaces)
instead of "%d" (pad with a zero) or strip the unwanted stuff:

:nnoremap <f4> /^<c-r>=substitute(strftime('%d'), '^0*', '',
'')<cr><bslash>><cr>

:cnoremap <f4><c-r>=substitute(strftime('%d'), '^0*', '', '')<cr>

==========================

For your more general case, I'd use vim's system() function to
call an external program or chain and return the output such as:

system("date | awk '{print $3}'")

however, that returns the trailing newline, so you'd have to
clean that out:

substitute(system("date | awk '{print $3}'"), '\D', '', 'g')


To get this into your search, you can either assign to the search
register:

:let @/ = substitute(system(...)...)

and then use n/N to navigate next/previous matches, or you can
use expression register (as I do above with control+R followed by
the "=" to allow you to enter an expression that gets evaluated
and returned in your context). You can read more at

:help @/
:h c_CTRL-R_=
:h substitute()
:h system()
:h strftime()

Hope this helps,

-tim

--
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

No comments: