richie
richie

Reputation: 2478

How do you delete all spaces that is 2 char long or more in vim?

I would like to delete every double space in a file open in vim, how is this done?

e.g delete space here

a  a

but keep the space here

a a

Upvotes: 2

Views: 142

Answers (4)

RunHolt
RunHolt

Reputation: 1972

Although the answer with { is most efficient, I find it easier to remember the space * solution. The correct solution would include three spaces (because * matches 0 or more).

:%s/   */ /g

Of course, this also assumes you want to replace two or more spaces with a single space.

Upvotes: 0

eckes
eckes

Reputation: 67037

:%s/\s\{2,}//g

Where the elements are:

  • %s substitute in the whole file
  • \s what to substitute: a space
  • \{2,} two or more occurrences
  • // replace with nothing (i.e. delete)
  • g do it on every occurrence on the current line (not only on the first)

The elements shall become clearer if you look at the anatomy of the substitute call:

s/PATTERN/REPLACEMENT/FLAGS

So, the PATTERN in our case is \s\{2,}, the REPLACEMENT is empty and FLAGS are just g. The range gets prefixed and is % which indicates the whole file. If you just want to do it on some lines, you could select the lines visually and then type :s....


Edit:
In your question, you wrote that you want to

delete every double space in a file

That's what I answered. If you want to replace two and more spaces by one, the command would be

:%s/\s\{2,}/ /g

Upvotes: 6

martiert
martiert

Reputation: 741

You can do something like:

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

Upvotes: 0

Rook
Rook

Reputation: 62528

How about this :%s/ */ /g

(there are two spaces in between / and *)

Upvotes: 0

Related Questions