vimtricks.wiki Concise Vim tricks, one at a time.

How do I collapse multiple consecutive spaces into a single space throughout a file?

Answer

:%s/\s\+/ /g

Explanation

The pattern \s\+ matches one or more whitespace characters (spaces, tabs). Replacing it with a single space throughout the file cleans up double-spaces, mixed tabs-and-spaces, and any other whitespace clutter — a common need when processing pasted text, legacy files, or data exports.

How it works

  • % — the range covering the entire file
  • s/ — substitute command
  • \s — any whitespace character (space or tab, equivalent to [ \t])
  • \+ — one or more occurrences
  • — replace with a single space
  • /g — global flag: replace all occurrences on each line

Example

Before:

name:    Alice      age:   30    city:     New York

After :%s/\s\+/ /g:

name: Alice age: 30 city: New York

To also strip leading and trailing whitespace on each line, chain it:

:%s/^\s\+//e | %s/\s\+$//e | %s/\s\+/ /g

Tips

  • The e flag suppresses errors on lines where the pattern is not found — safe to add when combining multiple substitutions
  • To normalize only within a visual selection (not the whole file): :'<,'>s/\s\+/ /g
  • If you only want to collapse spaces (not tabs), use \+ (two spaces then \+) or \ \+ instead of \s\+
  • For a more thorough cleanup, :retab converts tabs to spaces (or vice versa) based on your tabstop setting, and can be combined with this substitution

Next

How do I run a search and replace only within a visually selected region?