我想将 oooo 替换为 1, 2, 3, ...,如下例所示:
从
> cat demo.snippet
snippet anova.cca "anova.cca fun"
anova.cca(
,${oooo:object}
${oooo:,...}
,permutations = ${oooo:how(nperm = 999)}
,by = ${oooo:NULL}
)
endsnippet
snippet adonis "adonis fun"
adonis(
,${oooo:formula}
,data = ${oooo:NULL}
,permutations = ${oooo:999}
)
endsnippet
snippet anosim "anosim fun"
anosim(
${oooo:,...}
,${oooo:grouping}
,permutations = ${oooo:999}
)
endsnippet
到
snippet anova.cca "anova.cca fun"
anova.cca(
,${1:object}
${2:,...}
,permutations = ${3:how(nperm = 999)}
,by = ${4:NULL}
)
endsnippet
snippet adonis "adonis fun"
adonis(
,${1:formula}
,data = ${2:NULL}
,permutations = ${3:999}
)
endsnippet
snippet anosim "anosim fun"
anosim(
${1:,...}
,${2:grouping}
,permutations = ${3:999}
)
endsnippet
答案1
使用 python(版本 2 或 3):
from __future__ import print_function
oooo = None
with open('demo.snippet') as fp:
for line in fp:
if line.startswith('snippet '):
oooo = 1
while 'oooo' in line:
line = line.replace('oooo', str(oooo), 1)
oooo += 1
print(line, end='')
oooo
如果一行上出现多次,这也适用。
答案2
一个可能的 Perl 解决方案
perl -00 -F/\nendsnippet\n/ -pe '$n=1; s/oooo/$n++/ge' demo.snippet
答案3
另一个perl
,不占用内存中的整个文件:
perl -pe 's/oooo/++$i/ge; $i = 0 if /endsnippet/' <file
答案4
我使用下面的awk
代码,看起来效果很好。
awk 'BEGIN {x=0}
{ if ($0~/oooo/) {x++; gsub(/oooo/,x); print $0}
else if ($0~/snippet/) {x=0; print $0}
else {print $0}}' demo.snippet
编辑:这可以重写为
awk 'BEGIN {x=0}
/oooo/ {x++; gsub(/oooo/,x); print $0 ; next }
/snippet/ {x=0; }
{print } ' demo.snippet