Is there a Vim regex to delete all leading blank lines in the file?
text
more text
some more text
Should become:
text
more text
some more text
The following should do the job:
:%s/\%^\_\s*\n//
Here is an explanation:
\%^
match the beginning of the file\_\s
match any space character including new line*
repeat the match\n
match the last new lineI include the \n
to not match the leading space on the first non white-space line (line that that is only made of white-spaces)
Remark: If by blank line you mean empty line the regex is more simple:
:%s/\%^\n*//
:g/^\s\+/d
will work on every line
\_\s
item match new line and the *
make it work for multiple lines
Commented
Sep 30, 2022 at 1:44
Probably the most concise way to do this is with a range and the :delete
command:
:1,/\S/-1d
# Explanation
# -----------
d # Delete all the lines
:1, # in the range that starts at the beginning of the file
-1 # and ends one line before
/\S/ # the first line containing a non-whitespace character
If you don't want to delete whitespace-only lines it's even shorter:
:1,/./-1d
d # Delete all the lines
:1, # in the range that starts at the beginning of the file
-1 # and ends one line before
/./ # the first line containing anything
This is the method I use:
:g/^$/d
On the off chance that one or more of the lines isn't exactly blank, but contains whitespace, this variant on @mas answer works:
:g/^\s*$/d
You asked about leading blank lines. That implies to me that you don't want to delete any lines that come either between text-containing lines or after them. If that's the case, you want to put a range between the : and the g. In your sample's case, where it appears to me there are two blank lines, it'd look like:
:1,2g/^\s*$/d
:g
at all: :1,2d
. Although note that in the sample, there's actually only one blank line, so :1d
.
:
and the g
". But if you add a range specifying where the blank lines are, then you don't need the g
or the regular expression at all.
g
when I was testing it, but forgot to do so when I typed the answer.