vim:搜索替换为递增计数器

时间:2017-08-01 19:29:54

标签: vim

我想要做的是执行一个包含计数器的搜索替换模式,该计数器会跟踪它所做的替换次数并对它们进行编号。

这是一个例子。假设我有以下结构的代码块:

if (condition1(value)):
  array.push(value)
elseif (condition2(value)):
  array.push(modified(value))
elseif (condition3(value)):
  array.pop(value)

但假装有50个条件。我想在每个pushpop上面放置一个调试打印语句,以便我可以看到它运行时发生了什么。我可以在每个:%s/^\(\s\+\)\(array.p\)/\1print "DEBUG"\r\1\2/g之前使用相同的语句,但这没有用,因为打印件都是相同的。

我想要的是将print "DEBUG 1"放在第一场比赛之前,print "DEBUG 2"放在第二场比赛之前,等等,但为了做到这一点,我需要某种类型的计数器。

1 个答案:

答案 0 :(得分:2)

:let i = 0|g/\(push\|pop\)/let i = i + 1|put!='print \"DEBUG ' . i . '\"'

说明:

let i = 0                           define a control variable

g/\(push\|pop\)/                    mark all lines containing 'push' or 'pop'
                                    then execute what follows on each marked line

let i = i + 1                       increment the control variable

put!='print \"DEBUG ' . i . '\"'    put the debugging statement above

请参阅:help :global:help :let:help :put

相关问题