Reputation: 4278
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):
I'm using Sublime on Windows, if the line ending characters convention and regex engine does matter.
Upvotes: 2
Views: 4315
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,
After replace,
Upvotes: 9
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
Look close, you'll see that line 7 has disappeared in the replacement
Before
After
Upvotes: 3