Thursday, March 26, 2020

Visual Studio document delete lines containing

Often when I'm editing a text file in the Visual Studio document editor, I want to delete all lines containing a certain string of text. I always assumed this required some bothersome technique like writing macros or extensions, so for a decade or more I just dismissed it as too hard.

Today the issue returned when I wanted to trim all the boring lines out of a large log file to leave only the interesting ones. Suddenly (and I don't know why) the answer became obvious ... just use the standard Find and Replace using Regex patterns. So for example, if I want to delete all lines containing the text Boring Line I can check the Regular Expression option and use the find pattern ^.*Boring Line.*\r\n and replace it with nothing (an empty string).

This matches from the start of the line (^) to the end of the line including the Windows line terminator characters (\r\n) if it contains the desired string anywhere inside. Then each full matching line is replaced with nothing and is effectively deleted.

In my editor it looks like the following.