繁体   English   中英

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虽然:)

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

:%s/identifying text \zs\d\+\(.\d\+\)\=/\=(1.15+str2float(submatch(0)))/

感谢\\zs ,无需回忆主要文本。 感谢str2float()str2float()了一次加法(换句话说,1.15 + 2.87将给出预期结果,4.02,而不是3.102)。

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

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

:%s/\(identifying text \)\(\d\+\)\.\(\d\+\)/
  \=submatch(1) . (submatch(2) + 1) . "." . (submatch(3) + 1500)

(只有没有换行符)。

您的数字格式似乎是固定的,因此很容易转换为int并返回(删除点)添加11500并将点放回。

:%s/\.//
:%normal11500^A " type C-V then C-a
:%s/....$/.&/

如果您不想在所有行上执行此操作,但只有匹配“标识文本”的行替换所有%by'g / indentifying text /'

对于整数,您可以使用n ^ A将n添加到数字(并且n ^ X将其减去)。 我怀疑这是否适用于分数。

那么这可能不是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

使用宏

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM