Remove empty lines in code or text with Regexp

Regexp pattern to remove or replace empty lines in your code or text files to reduce the file size. Works in Sublime Text, Notepad++, VSCode, and other IDEs

When you are coding, you don’t consider the amount of space you leave behind. The focus remains on getting your code to work and ready to deploy. People use code linter to manage their code with a standard library. Sometimes you might just want to get the empty lines cleared in a text editor without a linter or for other text contents.

Removing empty lines on the whole file is not possible on a regular notepad. The text editor needs a regex capable find and replace feature. Regex or regexp, short for Regular Expression, is a pattern matching engine. We won’t go into details, as it is a big subject on its own. While IDEs will certainly have this feature, advanced text editors like Notepad++ or Sublime Text also have this feature inbuilt. We will use the regex feature to remove the empty lines, which is a straightforward process. Let’s start.

In Regex, the ‘\n’ symbol represents a line break and empty lines have two or more line breaks. We combine this information to form a regex pattern and use it to find and replace multiple line breaks with a single line break.

You need to turn on the regexp function in the “find and replace” section of your editor. In the find section, we include “\n\n+” which means find more than double new line breaks. In the replace section, we use a single line break as “\n”. On Sublime Text, it looks like this.

Pattern matching of empty lines in Sublime Text 3
Pattern matching of empty lines in Sublime Text 3

Now, just press on “Replace All” button and watch the empty lines disappear and you get a file without empty lines. If you want multiple empty lines to be reduced to 2 empty lines, use “\n\n” as your replace keyword.

Leave a Reply