Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim command to delete all but selected lines

Tags:

vim

line

I would like to do the inverse operation performed by

:g/pattern/d

i.e Delete all lines in a file which doesn't have pattern

like image 344
Jean Avatar asked Dec 16 '10 22:12

Jean


3 Answers

You can use v to select all line without pattern :
:v/pattern/d will achieve what you want to do.

See :help :v

like image 83
Xavier T. Avatar answered Nov 03 '22 22:11

Xavier T.


One way to do this is with a shell filter:

:%!grep pattern

This command passes your whole file (%) to a shell (!) which runs it through the grep pattern command and returns the output to your editor window.

like image 39
Greg Hewgill Avatar answered Nov 03 '22 23:11

Greg Hewgill


You can simply negate the pattern

:g!/pattern/d

This will delete all but the selected lines.

like image 30
85fce Avatar answered Nov 03 '22 22:11

85fce