提问人:Internet man 提问时间:11/16/2010 更新时间:11/17/2010 访问量:6803
Vim 搜索和替换,添加一个常量
Vim search and replace, adding a constant
问:
我知道这是一个很长的机会,但我有一个巨大的文本文件,我需要将给定的数字添加到与某些条件匹配的其他数字中。
例如。
identifying text 1.1200
identifying text 1.1400
我想将其(通过添加 1.15)转换为
identifying text 2.2700
identifying text 2.2900
通常我会在 Python 中执行此操作,但它是在 Windows 机器上,我无法安装太多东西。我有 Vim 虽然:)
答:
1赞
Colin Fine
11/16/2010
#1
对于整数,您可以只使用 n^A 将 n 加到一个数字中(并使用 n^X 减去它)。不过,我怀疑这是否适用于小数。
3赞
mb14
11/16/2010
#2
您的数字格式似乎是固定的,因此很容易转换为 int 并返回(删除点)添加 11500 并将点放回原处。
:%s/\.//
:%normal11500^A " type C-V then C-a
:%s/....$/.&/
如果您不想在所有行上都这样做,而只想在匹配“识别文本”的行上执行此操作,请将所有 % 替换为“g/识别文本/”
12赞
hobbs
11/16/2010
#3
您可以执行捕获正则表达式,然后使用 vimscript 表达式作为替换,类似于
:%s/\(identifying text \)\(\d\+\)\.\(\d\+\)/
\=submatch(1) . (submatch(2) + 1) . "." . (submatch(3) + 1500)
(仅没有换行符)。
1赞
joecks
11/16/2010
#4
好吧,这可能不是 vim 的解决方案,但我认为 awk 可以提供帮助:
cat testscript | LC_ALL=C awk '{printf "%s %s %s %s %.3f\n", $1,$2,$3,$4,$5+1.567 }'
和测试
this is a number 1.56
this is a number 2.56
this is a number 3.56
我需要 LC_ALL=C 来正确转换浮点分隔符,也许有一个更优雅的解决方案来打印字符串的开头/其余部分。结果如下所示:
this is a number 3.127
this is a number 4.127
this is a number 5.127
评论
0赞
joecks
11/16/2010
坝!只要读到它是一台 Windows 机器,所以忘记 awk :D
18赞
Luc Hermitte
11/16/2010
#5
以下是对霍布斯解决方案的简化和修复:
:%s/identifying text \zs\d\+\(.\d\+\)\=/\=(1.15+str2float(submatch(0)))/
多亏了 ,无需回忆前导文本。由于对整数进行了一次加法(换句话说,1.15 + 2.87 将给出预期结果 4.02,而不是 3.102)。\zs
str2float()
当然,这个解决方案需要最新版本的 Vim (7.3?)
评论
0赞
Lieven Keersmaekers
11/16/2010
+1.我什至可以让它工作(这说明了很多),但是有没有办法保留尾随的零。
2赞
Luc Hermitte
11/16/2010
用可能是?(:h printf()) ->printf()
...\=printf('%.4f', 1.15+str2float(......))
2赞
Bryce Guinta
10/23/2016
若要添加两个不带尾随小数的整数,请使用 。有关更多功能,请参阅str2nr
:h functions
1赞
SergioAraujo
11/17/2010
#6
使用宏
qa .......................... start record macro 'a'
/iden<Enter> ................ search 'ident*' press Enter
2w .......................... jump 2 words until number one (before dot)
Ctrl-a ...................... increases the number
2w .......................... jump to number after dot
1500 Ctrl-a ................. perform increases 1500 times
q ........................... stop record to macro 'a'
如果你刚才有 300 行这个模式制作
300@a
评论
0赞
Luc Hermitte
11/17/2010
OP 希望将一个数字(“给定数字”<单数)与 1.15 相加,而不是两个单独的数字。
评论