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