vi 搜索时替换为空

vi replaces with empty when searching

在 vi(来自 cygwin)中,当我搜索时:

:%s/something

它只是用空字符串替换了一些东西,比如

:%s/something//  .

我用谷歌搜索了一段时间,但没有真正提到这一点。有什么我应该添加到 .vimrc 或 .exrc 中以使其工作吗?

谢谢!

在 vi 和 vim 中,当您搜索模式时,只需键入 / 即可再次搜索它。可以理解,当没有指定模式进行搜索时,必须使用先前的模式。 (不过,您可以按 n 查找下一个事件)

同样,当您提供源(模式)并将替换留在替换命令中时,它假定替换为空,因此给定模式被替换为无字符(换句话说,模式被删除)

在你的情况下,你应该明白 % 代表整个文件(缓冲区)和 s 代表替代。要搜索,您可以简单地使用 /,后跟一个模式。要替换 ,您将使用 :s。您不必混淆搜索和替换。因此,不需要在 ~/.exrc 中进行此类设置。另外,请记住 / 足以搜索整个缓冲区,而 %/ 来说不是必需的。 / 隐式搜索整个缓冲区。

您可能还想看看 :g/Pattern/。通过在命令行中搜索 :help global:help :g 了解更多信息。

vim中的替换格式如下:

:[range]s[ubstitute]/{pattern}/{string}/[flags] [count]

在你的情况下,你已经从替换命令中省略了字符串,这里 vim 文档说明了它:

If the {string} is omitted the substitute is done as if it's empty. Thus the matched pattern is deleted. The separator after {pattern} can also be left out then. Example: > :%s/TESTING This deletes "TESTING" from all lines, but only one per line.

For compatibility with Vi these two exceptions are allowed: "/{string}/" and "\?{string}?" do the same as "//{string}/r". "\&{string}&" does the same as "//{string}/".

E146

Instead of the '/' which surrounds the pattern and replacement string, you can use any other single-byte character, but not an alphanumeric character, '\', '"' or '|'. This is useful if you want to include a '/' in the search pattern or replacement string. Example: > :s+/+//+

换句话说,:%s/something:%s;something:%s,something 具有相同的行为,因为 / ;, 在最后的例子被认为是仅作为简单的分隔符