Sublime Forum

How can I delete empty new lines at the start and at the end of a file?

#1

Hello. I’m new to the sublime forums and this is my first post here.
I want to know how I can delete empty new lines at the start of a file and at the end of it.
I know about a plugin called RegReplace but I do not know how to use it.
Can it help me with my problem? Thank you.

0 Likes

#2

you don’t need to use a plugin for this, just open the Find and Replace panel, enable RegEx mode and find \A\n+|(?<=\n)\n+\Z, replacing with blank.

If you don’t want the file to end in a newline character, you can remove the (?<=\n) bit. (But Sublime may re-add when you save the file if you have "ensure_newline_at_eof_on_save": true, set in your preferences.)

0 Likes

#3

Thank you very much! How can I make this to run when I save the file?

0 Likes

#4

to do something like that is where you probably do need to use a plugin :wink:

the documentation for RegReplace shows that it supports it:
http://facelessuser.github.io/RegReplace/usage/#apply-regex-right-before-file-save-event

I’ve never used this plugin, but I guess you would want config that looks a bit like this in your reg_replace.sublime-settings file:

"on_save": true,
"on_save_sequences": [
    {
        "file_pattern": ["*"],
        "sequence": ["remove_leading_and_trailing_newlines"],
    }
]

and like this in your reg_replace_rules.sublime-settings file:

{
    "replacements": {
        "remove_leading_and_trailing_newlines": {
            "find": "\\A\\n+|(?<=\\n)\\n+\\Z",
            "replace": "",
        },
}
0 Likes