Jens
Jens

Reputation: 9160

Remove only single trailing spaces in vim

When saving a Markdown file, I’d like to remove single trailing spaces at the end of the line and trim two or more trailing spaces to two.

I’ve tried

:%s/\([^\s]\)\s$/\1/gc

but that still matches two trailing spaces? Trimming two, seems to work though:

:%s/\s\{2,}$/  /gc

What am I missing here? Thanks!

Upvotes: 0

Views: 258

Answers (2)

Matt
Matt

Reputation: 15196

As an example,

%s/\s\+$/\=strlen(submatch(0)) >= 2 ? '  ' : ''/e

That is, capture all spaces at the end of line, and substitute it with two spaces if length of match is greater than 2. Pretty straightforward, I believe. See also :h sub-replace-expression.

Upvotes: 2

Jake Grossman
Jake Grossman

Reputation: 402

Inside [], all characters are taken literally. So you’re effectively saying “any character BUT \ or s", which all white space will match. What you want is \S (any non-white space character).

Also, you can make this simpler. Vim has special zero-width modifiers \zs and \ze to set the start or end point of a match, respectively. So, you could do the following:

:%s/\S\zs\s$//gc

Broken down:

  • %s/{pattern}//gc - replace every occurrence of {pattern} in the entire file with the empty string, with confirmation
  • \S - any non-whitespace character
  • \zs - start match here
  • \s - any whitespace character
  • $ - end of line

See the following :help topics:

:h :s
    :h :s_flags

:h pattern-atoms
    :h /[]
    :h /\zs
    :h /\ze
    :h /\$

Upvotes: 2

Related Questions