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!
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 /\$
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.