Tuesday, April 10, 2012

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

On 04/10/12 19:04, Zarko Coklin wrote:
> 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" :-)

Ah, that would make sense...I'm likely the guilty party.

> 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.
>
>> :v/cat\|.*\n.*cat\|\%(cat.*\n\)\@<=./d

If you just want the line with one-before and one-after, the
above one works nicely. If you want to do an arbitrary number of
lines above/below, the decorate/process/undecorate is far friendlier

:g/cat/sil! -8,+4s/^/XXX
:v/^XXX/d
:%s/^XXX

would give you 8 lines of context before and 4 lines of context
afterward. Note that, if these ranges overlap (such that 8 lines
before ends up within the 4 lines after) you'll get them
decorated twice, so you might have to use that last ":%s/^XXX"
multiple times. In this case "XXX" is some arbitrary text that
never appears at the beginning of a line in your actual document.

If you want search bracketing instead of fixed-line bracketing,
such as if you had C-like code:

int foo(bar) {
aaa;
bbb;
cat;
ccc;
ddd;
}

you can change the absolute ranges ("-8,+4") to relative search
ranges like

g/cat/sil! ?^\<.*{$?;/^}/s/^/XXX

which is the range from "search backwards for a line that starts
with a Word character in the first column and has a '{' at the
end of the line" through "then, from there, search forward until
you find a '}' as the first character of the line" and then put
"XXX" in front of each line.

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