是否可以用 vim 中的 n 标记模式的第 n 次出现?

Is it possible to mark the n-th occurrence of a pattern with n in vim?

假设我有如下文本。

The man is walking, and the man is eating.

我应该如何使用替换将其转换为以下内容?

The man 1 is walking, and the man 2 is eating.

我知道我可以使用 :%s/\<man\>//gn 来计算单词 man 的出现次数并且我知道 /\%(\(pattern\).\{-}\)\{n - 1}\zs 可以找到第 n 次出现的模式。但是如何标记第 n 次出现?

真诚感谢任何帮助;提前致谢。

您需要一个计算出现次数的非纯函数,并使用该函数的结果。

" untested
let s:count = 0
function! Count()
    let s:count += 1
    return s:count
endfunction

:%s/man\zs/\=' '.Count()/

您可以使用宏来做到这一点。 首先,搜索模式,例如 /man /e.

让我们为计数创建一个变量,例如 :let cnt=1

现在,让我们清除a寄存器。

qa 开始录制。

n

i,然后,Ctrl+R 输入=。输入 cnt。 count 的值被插入那里。 然后,输入 :let cnt=cnt+1.

按 Escape。

q停止收银。

现在,键入 :%s/man //gn 以获取出现次数。

现在,您知道出现的次数,比如 10。然后,您将按 10@a。 所有出现都将附加一个数字,每次出现都会递增。