Genschman
Genschman

Reputation: 187

vim search and copy lines including pattern

I use the following VIM command, to copy all lines including a pattern to the end of the file :g/pattern/t$
But I also want the previous or the line below of the matched line copied too

Upvotes: 3

Views: 665

Answers (1)

romainl
romainl

Reputation: 196466

In:

:g/pattern/t$

:t is an ex command which, like all ex commands, can take a range.

The following command would copy lines 1-13 after the last line:

:1,13t$

Beside absolute line numbers, you can use relative numbers:

:-3,+5t$

and, really, anything that can be translated to a line number:

:?foo?,'et$

In your case, you can use a range to tell Vim to copy the marked line, the one above (-1), and the one below (+1):

:g/pattern/-1,+1t$

Or, slightly shorter:

:g/pattern/-,+t$

Upvotes: 4

Related Questions