8

I have the following lines. I'd like to replace multiple spaces with a single space in vim. How can I achieve this?

Thanks in advance.

Percent                      I4-15
b Percent and Fractions                   16-19
c Percent and Decimals                    20
d EstimatingPercents                     21
13

You can do it with a vim regex.

:%s# \+# #g

| improve this answer | |
  • 2
    Or use "\s" instead of " " to match any kind of whitespace. – Heptite Feb 20 '14 at 1:18
  • Thanks it worked. What is #, \+# etc? Can you explain it please? – shinokada Feb 20 '14 at 1:31
  • 4
    The basic construct of the command is s#search#replace#. Sometimes you see it as s///. The % before the s tells the regex to work on all lines in the vim buffer, not just the current. The space followed by \+ matches one or more spaces. The trailing g tells the regex to match multiple times in a single line. – User123456 Feb 20 '14 at 1:50
  • If you are bothered by replacing a single space with a single space (wasted effort) then, instead of ` \+` (one or more spaces) you can use ` \{2,\}` (two or more spaces) or __\+ (a space followed by one or more spaces--I am using "_" instead of " " because HTML refuses to display two consecutive spaces). – benjifisher Feb 20 '14 at 1:57
  • 1
    For single line: :s/\s\+/ /g – denis.peplin May 13 '15 at 10:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.