计算 Vim 中的出现次数而不标记缓冲区已更改

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

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

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

还有比这更优雅的计数方法吗?

37281 次浏览

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

:%s/pattern-here//gn

这被描述为 官方提示

:!cat %| grep -c "pattern"

虽然不是 Vim 的命令,但它能满足你对 Vim 的需求。
如果需要经常使用它,可以将其映射到命令。

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

Vimgrep 是你的朋友:

vimgrep pattern %

节目:

(1 of 37)
: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

将光标放在要计数的单词上,然后执行以下操作。

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

参见 :h c_ctrl-r_ctrl-w