In my Visual Studio (2010 C#) solution, I need to delete all lines of code that contain a matching string pattern.
For example, I want to delete all lines that contain ".BackColor = System.Drawing.Color.Yellow;". The Find and Replace feature of Visual Studio isn't good enough, because you cannot tell it to wipe out the matching lines.
So I think I would need a macro for that. Any help is appreciated.
*\n? Then ALT - Enter will select all lines that match and Delete will eliminate them including the lines they occupied. You can also fire the replace with an empty field, instead of using a keyboard combination. It works fine also.
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.
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.
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)
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With