ellockie
ellockie

Reputation: 4278

Regex: how to remove the last, empty line?

I want to remove the very last, empty line from a file using regex search-replace. Matching a new line with an end-of-line marker:

\n$

seem to be a step in a good direction, but it simply matches all empty lines (new lines character followed by an empty line, to be precise):

enter image description here

I'm using Sublime on Windows, if the line ending characters convention and regex engine does matter.

Upvotes: 2

Views: 4315

Answers (2)

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

You can use \s*\Z to select all whiltespaces including newlines and \Z marks the end of input and replace it with empty string.

This will indeed get rid of all the newlines at the end of text (one or more) even when those newlines may contain spaces (not easily visible), which might be helpful, because in general we want to get rid of extra useless lines at the end of text in file.

Just in case if you want to get rid of ONLY ONE line from end of file, you can use \n\Z instead of \s*\Z.

Please check following screenshots demonstrating same.

Before replace,

enter image description here

After replace,

enter image description here

Upvotes: 9

Yassin Hajaj
Yassin Hajaj

Reputation: 22005

The following regex should help you achieve it

\n\s*$(?!\n)

It begins at line 6, and matches everything at line 7 and deletes it. Basically it searches for the line that is empty and doesn't have a carriage return at the end

Demo 1

Look close, you'll see that line 7 has disappeared in the replacement

Demo 2 (in Visual Studio Code)

Before

enter image description here

After

enter image description here

Upvotes: 3

Related Questions