Tuesday, April 10, 2012

Re: Search a pattern and provide a context (few lines above and below)

Thanks Tim!

I think I found somewhere on the Internet an example how to use a 'z'
comnand. If I am not mistaken the author signed himself with "tim" :-)

BTW, my example is simplified and the solution should get the line
which has a pattern (could be at the beginnig, middle or end). Which
if your suggested solutions would work best? Also explain how to tweak
number of lines above/below.

Thanks!
Z

On 2012-04-10, at 7:39 PM, Tim Chase <vim@tim.thechases.com> wrote:

> On 04/10/12 16:49, Zarko Coklin wrote:
>> 1. dog
>> 2. cat //<- I want to keep this line and one line above and one line below
>> 3. mouse
>> 4. cow
>> 5. horse
>> 6. dolphin
>> 7. whale
>> 8. cat //<- I want to keep this line and one line above and one line below
>> 9. sheep
>> 10. bat
>
> I think to do this, it would be easiest to do some sort of decorate/process/undecorate pass such as
>
> :g/cat/sil! -,+>
> :v/^\s/d
> :%<
>
> which works with your example (where everything is left-justified). Your decoration and deletion-of-undecorated could be any other marker such as
>
> :%s/.*cat/XXX&
> :v/^XXX/d
> :%s/^XXX
>
> Alternatively, you can do it in one pass:
>
> :v/cat\|.*\n.*cat\|\%(cat.*\n\)\@<=./d
>
> which basically just enumerated the 3 conditions on which a line can match ("cat" is on the line, there's stuff followed by a newline followed by stuff containing "cat", or you assert that the previous line contains "cat").
>
> The first one scales better to greater numbers of context lines (you can easily adjust the number of lines backwards & forwards, or do the adjustment with searches rather than relative line-number offsets); while for your particular case, the all-in-one might be easier.
>
>> I believe the following command does something similar to what I need
>>
>> :g/192.168.4.2:5120 ->/z#.3
>
> It warms my grey-beard heart to see other people employing the very underutilized :z family of commands. :-)
>
> -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: