Refactoring Python imports in Vim

I had a lot of lines that looked like this:

import abc as cache_abc  
import csad as cache_csad  
import qwewe as cache_qwewe  
import oiu as cache_oiu  

Most module names in this example is made up. I wanted to keep only the imports and drop the rest. If you have around 100 lines doing it manually is tedious. Vim to the rescue!

Let's start by recording a macro that filters single line:

<Home><Esc>qa2f Dq  

Translating Vim incantation into plain English:

  1. Goto start of the line
  2. Enter normal mode
  3. Start recording a macro a
  4. Find second space
  5. Delete rest of the line
  6. Stop recording macro a

Now pressing v to enter visual mode, select all the lines you want to refactor and enter:

:normal @a

Which uses the normal mode command to essentially enumerate all the visually selected lines and execute the pre-recorded macro a .