Remove Lines in VIM with Only Whitespace

2

Is there a vim idiom for removing all lines from a file that have only whitespace (including newlines)?

AJ.

Posted 2011-05-27T19:06:21.017

Reputation: 3 491

Answers

2

The d command takes a range, and the range can be a regex.

:g/^\s*$/d

Ignacio Vazquez-Abrams

Posted 2011-05-27T19:06:21.017

Reputation: 100 516

so, normally I use something like :%s/search/replace/g to do global search and replace. is :g equivalent to :%s with g option? – AJ. – 2011-05-27T19:12:22.220

: puts vim in command mode. g is a modifier for the range. % is the range that means "all lines". s is the substitute command. d is the delete command, which takes no options. – Ignacio Vazquez-Abrams – 2011-05-27T19:15:55.607

@Ignacio: On first read I saw that d takes no hostages ... – Benjamin Bannier – 2011-05-27T19:16:56.343

@honk: Unfortunately it does. Fortunately they're only a p away. – Ignacio Vazquez-Abrams – 2011-05-27T19:17:51.303

ah, substitute vs delete, understand. thanks! – AJ. – 2011-05-27T19:23:12.367

2:g[lobal] applies an ex command to the lines that match a given pattern. So, in the given solution :global will search for lines with 0 or more white space (/^\s*$/) and apply the :d[elete] command on them. See :h :global for more details and alternatives. – Raimondi – 2011-05-27T19:38:17.290

the :v version of :g is also very useful since it applies the command to the lines that don't match the pattern. For example the same could be accomplished with the following: :v/\S/d – Neg_EV – 2011-06-21T22:15:28.590