I want to remove repeated spaces, but not if they occur at the start of a line (indendation).


line 1
  hi  there      i      have    spaces


line 1
  hi there i have spaces

I've gotten as far as s/^\s\+/ /g, but that deletes only duplicate spaces that are at the start of the line. I need to know how to negate the ^.

2 Answers 2


You don't need to match the start of the line. Instead, match any non-whitespace character. This should work:

s/\S\zs\s\{2,}/ /g


  • \S\zs match any non-whitespace character and set start of pattern match after the character
  • \s\{2,} match at two or more spaces

@KarlYngveLervåg's answer is probably simpler, but you can also achieve this using your original idea of negating the ^ atom. To do so you can use negative look behind. (See :help /\@<!) which causes an atom to match only when it doesn't follow another specified atom, in this case the ^ start of line.

The naive expression below where we simply add this in to your existing expression doesn't work, however, because, if your line starts with multiple spaces, the second space on the line, and all those that following it, do not immediately follow the start of the line, and thus match:

:s/^\@<!\s\+/ g

So to fix this, we also need to include these start-of-line spaces as part of the thing we don't want our spaces to follow:

:s/\(^\s*\)\@<!\s\+/ /g

As @KarlYngveLervåg also noted, we can make this cleaner by only matching when there actually are multiple spaces:

:s/\(^\s*\)\@<!\s\{2,}/ /g

As a final touch, we can simplify this by using the very magic \v atom (:help /\v), so we don't have to do quite so much \escaping.


    ┌──────────────── 1.     \v - Using "very magic",
    │              ┌─ 2.  s{2,} - Match two or more spaces,
   ┌┤         ┌────┤
   ││         │    │
:s/\v(^\s*)@<!\s{2,}/ /g
     │    ││ │
          │  └─────── 3.    @<! - That do not follow,
          └────────── 4. (^\s*) - The start of the line followed by
                                  any number of spaces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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