In VIM, how can I delete all lines until a regular expression is executed?

I'm sure this was answered, but the request is too complicated for google.

In short, I am trying to remove many deprecated methods from some code. So I look at the file, and when I see the method I want to delete, I delete every line until I see a line starting with a tab and then the line "def".

I think VIM should let me create a simple macro to do this, but the trick eludes me.

Here is what I want to remove.

def Method_to_Delete(self): """ @return Control ID : @author """ results = {} results['xx'] = "thingy" results['yy'] = 'thingy2' return results def Method_to_Keep(self): """ This is a method that does something wonderful!!! @return Control ID : @author """ results = {} results['xxx'] = "WhooHoo!" results['yyy'] = 'yippee!!' return results 

I want to have a cursor on the line with "def Method_to_Delete" and do something that will be deleted until it includes "def Method_to_Keep"

There should be a better way than a few dd commands.

+7
source share
2 answers

Vim searches are actually text objects! This means that you can simply:

 d/\s*def 

Then just repeat the command with . optional.

+13
source

Use ex command :delete with range

 :,/Keep/-1d 

Explanation

  • Full command:: :.,/Keep/-1delete
  • .,/Keep/-1 is the range in which the delete command will act
  • . means the current line.
  • b / c we use the range and starting from the current position . can be assumed and discarded
  • /Keep/ find the line that matches "keep"
  • /Keep/-1 - search for a line, which then subtracts one line
  • :delete may be shorted to :d

See details

 :h :range :h :d 
+11
source

All Articles