Vim 搜索和替换,添加常量
我知道这是一个很遥远的事情,但我有一个巨大的文本文件,我需要将给定的数字添加到符合某些条件的其他数字中。
例如。
identifying text 1.1200
identifying text 1.1400
我想将其(通过添加 1.15)转换为
identifying text 2.2700
identifying text 2.2900
通常我会在 Python 中执行此操作,但它是在 Windows 计算机上,我无法安装太多东西。不过我有 Vim :)
I know this is a long shot, but I have a huge text file and I need to add a given number to other numbers matching some criteria.
Eg.
identifying text 1.1200
identifying text 1.1400
and I'd like to transform this (by adding say 1.15) to
identifying text 2.2700
identifying text 2.2900
Normally I'd do this in Python, but it's on a Windows machine where I can't install too many things. I've got Vim though :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这是霍布斯解决方案的简化和修复:
感谢
\zs
,无需回忆前导文本。感谢str2float()
对整个数字进行一次加法(换句话说,1.15 + 2.87 将给出预期结果,4.02,而不是 3.102)。当然这个解决方案需要最新版本的 Vim(7.3?)
Here is a simplification and a fix on hobbs' solution:
Thanks to
\zs
, there is no need to recall the leading text. Thanks tostr2float()
a single addition is done on the whole number (in other words, 1.15 + 2.87 will give the expected result, 4.02, and not 3.102).Of course this solution requires a recent version of Vim (7.3?)
您可以执行捕获正则表达式,然后使用 vimscript 表达式作为替换,例如
(仅不带换行符)。
You can do a capturing regex and then use a vimscript expression as a replacement, something like
(only without the linebreak).
你的数字格式似乎是固定的,所以很容易转换为int并返回(删除点)添加11500并将点放回去。
如果您不想在所有行上执行此操作,而只想在与“识别文本”匹配的行上执行此操作,请将所有 % 替换为“g/识别文本/”
Your number format seems to be a fixed one, so it's easy to convert to int and come back (remove the dot) add 11500 and put the dot back.
If you don't want to do that on all the lines but only the one which match 'identifying text' replace all the % by 'g/indentifying text/'
对于整数,您只需使用 n^A 将 n 添加到数字(并使用 n^X 减去它)。我怀疑这是否适用于小数。
For integers you can just use n^A to add n to a number (and n^X to subtract it). I doubt whether that works for fractional numbers though.
好吧,这可能不是 vim 的解决方案,但我认为 awk 可以提供帮助:
并且我需要 LC_ALL=C 的测试
来正确转换浮点分隔符,也许有一个更优雅的解决方案来打印开头/其余部分字符串。结果如下:
Well this might not be a solution for vim but I think awk can help:
and the test
I needed the LC_ALL=C for the correct conversion of the floating point separator, and maybe there is a more elegant solution for printing the beginning/ rest of the string. And the result looks like:
请使用宏
如果您现在有 300 行带有此模式的行,
Using macro
if you have 300 lines with this pattern just now making