Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In VIM how can I delete all lines until a regex is met?

Tags:

vim

I am sure this has been answered, but the query is a bit too complex for google.

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

I am thinking VIM should let me create a simple macro to do this, but the trick is escaping me.

Here is the kind of thing 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 the cursor on the line with "def Method_to_Delete" and do something that will delete up until but not including "def Method_to_Keep"

There has got to be a better way than multiple "dd" commands.

like image 684
Skip Huffman Avatar asked Aug 09 '12 11:08

Skip Huffman


People also ask

How do I delete multiple lines of code in Vim?

Deleting Multiple Lines in Vi and VimInstead of simply pressing dd, you can specify the number of lines you want to delete. For example, typing 3dd will delete the next three lines from the file. You can also use wildcard characters in the aforementioned command.

How do I delete a line not matching in Vim?

The ex command g is very useful for acting on lines that match a pattern. You can use it with the d command, to delete all lines that contain a particular pattern, or all lines that do not contain a pattern.


2 Answers

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

d/\s*def

Then, simply repeat the command with . as desired.

like image 150
guns Avatar answered Oct 23 '22 17:10

guns


Use the :delete ex-command with a range

:,/Keep/-1d

Explanation

  • The full command would be :.,/Keep/-1delete
  • .,/Keep/-1 is the range in which the delete command will act
  • . means the current line.
  • b/c we are using an range and starting from the current position the . can be assumed and dropped
  • /Keep/ search for the line that matches "Keep"
  • /Keep/-1 is search for the line that matches then subtract one line
  • :delete can be shorted to :d

For more help see

:h :range
:h :d
like image 34
Peter Rincker Avatar answered Oct 23 '22 17:10

Peter Rincker