Robottinosino
Robottinosino

Reputation: 10902

Vim: open a new buffer containing all the lines of the current file matching a pattern

I am editing a Python file in Vim and I have a few lines to extract: all lines matching pattern REGEX.

I can list all of these lines by :g/REGEX.

How can I open a new buffer with the contents of the selection returned by the command above?

Right now, I am resorting to exiting the editor and using cat and grep to actually create a new file... there must be an integrated way?

Upvotes: 0

Views: 818

Answers (2)

Austin R
Austin R

Reputation: 795

If you're cool with command line Vim rather than gVim I believe:

vim `grep REGEX file.txt` 

Would do the trick.

Upvotes: 0

kev
kev

Reputation: 161994

Try this one:

$ vim file.txt

:e new.txt
:0r!grep REGEX #

The last command calls external grep with REGEX and alternative buffer name #(same as file.txt), then reads the result to current buffer(new.txt)


Also try this one:

$ vim file.txt

:v/REGEX/d
:w new.txt

Upvotes: 3

Related Questions