为了知道当前缓冲区中某个模式存在多少次,我这样做:

:%s/pattern-here/pattern-here/g

它给出了模式出现的次数,但显然很麻烦,并且还具有设置“已更改”状态的副作用。

有没有更优雅的计数方式?

有帮助吗?

解决方案

为了避免替换,请将第二个模式留空,并添加“n”标志:

:%s/pattern-here//gn

这被描述为 官方提示.

其他提示

:help count-items

在 VIM 6.3 中,您可以这样做。

:set report=0
:%s/your_word/&/g    # returns the count without substitution

在 VIM 7.2 中,您可以这样做:

:%s/your_word/&/gn   # returns the count, n flag avoids substitution
:!cat %| grep -c "pattern"

它不完全是 vim 命令,但它会给你 vim 所需的东西。
如果需要经常使用,可以将其映射到命令中。

Vim 脚本 索引搜索 增强了 Vim 搜索命令以显示“At match #N out of M matches”。

将光标放在要计算的单词上并执行以下操作。

:%s/<c-r><c-w>//gn

:h c_ctrl-r_ctrl-w

vimgrep 是你的朋友:

vimgrep pattern %

显示:

(1 of 37)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top