Vim搜索和替换,添加常量

Int*_*man 16 regex vim data-manipulation

我知道这是一个很长的镜头,但我有一个巨大的文本文件,我需要将一个给定的数字添加到符合某些标准的其他数字.

例如.

identifying text 1.1200
identifying text 1.1400
Run Code Online (Sandbox Code Playgroud)

我想改变它(通过添加说1.15)

identifying text 2.2700
identifying text 2.2900
Run Code Online (Sandbox Code Playgroud)

通常我会在Python中执行此操作,但它是在Windows机器上,我无法安装太多东西.我有Vim虽然:)

Luc*_*tte 18

这是对hobbs解决方案的简化和修复:

:%s/identifying text \zs\d\+\(.\d\+\)\=/\=(1.15+str2float(submatch(0)))/
Run Code Online (Sandbox Code Playgroud)

谢谢\zs,没有必要回忆起主要文本.由于str2float()在整数上进行了一次加法(换句话说,1.15 + 2.87将给出预期结果,4.02,而不是3.102).

当然这个解决方案需要最新版本的Vim(7.3?)

  • 用'printf()`可能是?(:h printf()) - >`...\= printf('%.4f',1.15 + str2float(......))` (2认同)
  • 要添加两个不带尾随小数的整数,请使用`str2nr`.有关更多函数,请参阅`:h functions` (2认同)

hob*_*bbs 10

您可以执行捕获正则表达式,然后使用vimscript表达式作为替换,类似于

:%s/\(identifying text \)\(\d\+\)\.\(\d\+\)/
  \=submatch(1) . (submatch(2) + 1) . "." . (submatch(3) + 1500)
Run Code Online (Sandbox Code Playgroud)

(只有没有换行符).