Pratik Khadloya
Pratik Khadloya

Reputation: 12869

Delete all lines except the one that matches a pattern and also keep 2 lines before the match

Is it possible in vim to delete all the lines except for the ones that match a pattern and also keep a couple of lines before and after (like a context in grep).

Upvotes: 3

Views: 1433

Answers (3)

Don Reba
Don Reba

Reputation: 14041

Another pure-vim solution that copies the output to a register:

:redir @a
:g/pat/z.5
:redir END

Command :z.5 works like grep -2. Check help about it - it can be used for some interesting effects.

Command redir @a redirects output to register a, and redir END ends redirection.

But if you just want to see the found lines with some context, then :g/pat/z.5 might be your best option.

Upvotes: 4

Peter Rincker
Peter Rincker

Reputation: 45117

A pure vim solution using :global

:let @a=""
:g/pat/-2,+2y A
:%d_
:pu a
:1,2d_

Overview:

Yank 2 lines on each side of the pattern and append to a register. Then delete the buffer and replace with the contents of the register.

Note: Use @merlin2011's grep version. It is the simplest.

For more help see:

:h :range
:h :let-@
:h :g
:h quote
:h :d
:h :pu
:h registers

Upvotes: 3

merlin2011
merlin2011

Reputation: 75565

Since you mentioned grep, the cleanest way is probably to simply invoke grep on the whole buffer.

%!grep -2 pattern_to_match

I will update if I find a pure-vim solution, but I doubt it will be cleaner than the above solution.

Upvotes: 5

Related Questions