Extract lines to file


In almost any text-editing use-case it can be necessary to extract portions of your current file into a separate file. The easiest way to do this in Vim is with w. Here’s a workflow I recently used when extracting portions of a class to a new library:

  • shift-v to visually select some lines
  • :w path/to/new/file.rb<Enter> to save those lines to a new file
  • gv to reselect the last visual selection
    (Read that post if you haven’t already. It’s one of our most popular!)
  • d to delete that selection

Another variation on this is to use >> before your filename to append rather than overwrite.

  • :w >>path/to/new/file.rb<Enter> appends the lines to the existing file

There’s a video below where I demonstrate these in action, check it out!

Ruby Developer?

If you’re a Ruby developer, or more specifically a Rails developer, then you should already be using tpope’s rails.vim. Built into to this essential plugin is an :Extract command that will extract the highlighted lines to their own file. From a model, it will extract to a Concern. From a View, it will extract to a Partial. This extra command adds some niceties that the vanilla-Vim version above can’t offer, like removing the extracted code and leaving behind a reference to it.

And as an aside, we are both professional Ruby developers ourselves, and we’ve developed years of experience honing Vim for Ruby work. So we’ve opened up preorders for our Vim for Rubyists email course. Check it out!

Okay, now on to a brief demo video:

How useful was this tip?

Average rating 4.2 / 5. Vote count: 270

No votes so far! Be the first to rate this tip.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Colin Bartlett

105 Posts

Vim enthusiast and software developer for more than 20 years.
View all posts