Last Updated: February 25, 2016
·
14.96K
· jaredonline

Removing whitespace with Vim

If you read my previous pro-tip and moved from Sublime Text 2 or TextMate to MacVim, you're probably noticing lots of really annoying blue dots at the end of lines in your files.

Those blue dots represent whitespace with no character before the newline character in your file (which is why they don't show where your tabs are for code indentation).

Finding all the blue dots and getting rid of them can be a pain in the arse if your Vim-fu skills are just getting started.

Fortunately, there's a single command to do it for you:

:%s/\s\+$//g

Let me break that down for you

:

Start inputing a new command. Just like :w or :q or :wq

%s

This command is the "substitute on all lines of the file" command.

/\s\+$

This is Vim's RegEx for "1 or more whitespace character anchored to the end of the line".

//

The substituted text is.... nothing. We want to delete it all [=

g

The "global" flag, which tells Vim to search the entire document.

When you put those all together, you get a sweet, streamlined, blue dot free file [=

EDIT: as @akhilravidas points out, you don't actually need the g flag in this command, so you can simplify the command to:

:%s/\s\+$

3 Responses
Add your response

Your regex can atmost match once in a line (because of $), so g doesn't do anything. Although the flag's name is global, it actually means global in a given line and not doc (I'd guess because of evolution from ed commands).

over 1 year ago ·

@akhilravidas Thanks! I didn't realize that... I was actually unsure what the difference between using %s and the g flag was, but now it makes sense.

over 1 year ago ·

@jaredonline Yeah, the two sometimes trips people. :help s_flags has all info about flags that can be used with substitute command

over 1 year ago ·