Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vim search and copy lines including pattern

Tags:

vim

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

like image 427
Genschman Avatar asked Jun 28 '26 01:06

Genschman


1 Answers

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$
like image 200
romainl Avatar answered Jul 01 '26 06:07

romainl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!