无法在 Vim 中用新行替换空格

我知道 线

我跑步

:%s/ /s/\n/g

我明白

E488: Trailing characters

第二个例子

我跑步

:%s/ /\n/g

我明白

text^@text

我运行相同的代码也与以下设置分开

set fileformat=unix

还有

set fileformat=dos

如何在 Vim 中用新行替换?

69902 次浏览

:%s/ /Ctrl vReturn/g

Where Ctrl v is Control-key plus key v and Return is the return key (the one on the main keyboard, not the enter key on the numpad). The other characters are typed as usual.

If this is entered correctly, the sequence Ctrl vReturn will display as the characters ^M, typically in a different color, to indicate that they are special. Note that actually typing ^M will not work.

Also note that in Vim for windows, it's Control-q instead of Control-v (as that is paste).


Ctrl-v also allows entering other "special" keys via the keyboard. It is also useful for e.g. Tab or Backspace.

Try

%s/ /\r/g

Enter the following:

:s/ /

and now type Ctrl-V or Ctrl-Q (depends on your configuration) and hit the Enter key. You should now have:

:s/ /^M

Finish it off:

:s/ /^M/g

and you are good to go.

Try either

For Unix:

:1,$s/\ /\n/g

For Windows:

:1,$s/\ /\r/g

This contains an escape character for the space.

Specifically to answer your problem with trailing characters, this is the regex you specified:

:%s/ /s/\n/g

You have too many /. What happens is that you replace ' ' with s, and then you tag on this after the substitution: \n/g

I think you meant this:

:%s/ \s/\n/g

Note that your /s was changed to \s. Now the substitution will replace one space followed by one whitespace of any kind (space or tab) with \n. I doubt if this solve the problem or replacing space with a newline, but it should explain the error message.