Visual Studio macro to find a string and delete matching lines

Building upon @HolgerJeromin's answer: instead of guessing the right indentation match (could be tabs could be spaces could be more or less), I prefer matching the beginning of the line using the ^\s* pattern.

For example, to remove all lines having a ProducesResponseType attribute, I use

^\s*\[ProducesResponseType.*\n

(works on Windows too using VS 2019).


With Visual Studio 2015 this worked for me. Open Search window, check the "use regular expressions" checkmark. Fill "find what" with

.*myCodeHere.*\r?\n

fill "replace" with an empty string.


You can use the "Find and Replace" feature of Visual Studio to delete matching lines.

The key is to match the whole line including the end of line character as well. You can do this in wildcard or regular expression mode. In wildcard mode, begin the expression with * and end the expression with *\n. The asterisks will match any number of characters, and the \n will match the end of line character.

In your case, your find query would be "*.BackColor = System.Drawing.Color.Yellow;*\n". The replace field should then be left blank.


To enable wildcard mode, select 'Wildcards' in the 'Use:' field of the 'Find options' section of the 'Find and Replace' dialog.

Example showing how to turn on wildcard mode


I tend to create macros in VS by running the macro recorder then editing the resulting code.

So, manually search for the pattern, and press F3. Stop the macro then (or press the line-start key, select to end of line, press delete and then stop the macro).

Edit the macro, the command to delete a line is:

DTE.ActiveDocument.Selection.SelectLine()
DTE.ActiveDocument.Selection.Delete()

You can set the find text with FindText:

DTE.ActiveDocument.Selection.FindText(".BackColor = System.Drawing.Color.Yellow;", vsFindOptions.vsFindOptionsFromStart)