我有这个带数字的文字:
My numbers are 04, and 0005
My numbers are 05, and 0006
My numbers are 06, and 0035
My numbers are 07, and 0007
My numbers are 08, and 0009
这是我经常用来增加或减少选择/块选择/列中的数字的代码:PE 将上面文本中的最后 4 个数字递增为 8:
'<,'>s/%V<d{4}>/=submatch(0)+8/g
但我今天注意到它做了奇怪的事情。这是输出:
My numbers are 04, and 13
My numbers are 05, and 14
My numbers are 06, and 37 <---
My numbers are 07, and 15
My numbers are 08, and 17
- 它删除了前导零(如果有前导零,我想保留它们如果没有前导零,则不添加它们)
- 它向除 37 以外的所有数字添加了 8,其中添加了 2。(为什么?
谁能帮我找到一个正则表达式来添加/减去数字从选择(或块选择)而不丢失前导零?
注意:
我注意到控件A + 控件x保留前导零并按照我的意愿完成工作,但是:
- 我已经看到它不能在替代命令中使用('<'>s/)
- 我不知道如何将 p.e. 200 添加到数字列表中(200 x ?
前导零使数字8-based
。
(0035)8 == (29)10
你可以在 vim 中测试:
:echo 0035 == 29
它会打印1
(真)。
试试这个:
:%s/(<[0-9]{4}>)@=0*([0-9]*)/=submatch(2)+8/
这个?
:%s/v[0-9]{4}/=printf("%04d", substitute(submatch(0), '^0+', '', 0)+8)/
编辑
@Remonn,您应该在问题中提供正确的示例输入。 上面的行适用于您的示例。
对于您的新要求,请查看以下行:
输入:
40
20
120
0500
230
0000000020
00000000000005000
VIM CMD:
:%!awk '{if($0~/^0/){f="%"length($0)"d";$0+=8; s=sprintf(f,$0); gsub(/ /,"0",s);}else s=$0+8;print s}'
将文件更改为:
48
28
128
0508
238
0000000028
00000000000005008
在我的cmd中,我使用了"%",您可以选择(v)要做技巧的数字,然后尝试使用我的cmd。
祝你好运
默认情况下,Vim 将以 0
开头的数字视为八进制。
出于这个原因,我在我的 .vimrc 中有这个:
set nrformats-=octal " Don't bother with octal, I never use it