【问题标题】:Vim search and replace, adding a constantVim 查找替换,添加一个常量
【发布时间】:2011-05-10 18:19:03
【问题描述】:

我知道这是一个远大的目标,但我有一个巨大的文本文件,我需要将给定的数字添加到符合某些条件的其他数字。

例如。

identifying text 1.1200
identifying text 1.1400

我想将它(通过添加 1.15)转换为

identifying text 2.2700
identifying text 2.2900

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

【问题讨论】:

    标签: regex vim data-manipulation


    【解决方案1】:

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

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

    感谢\zs,无需回忆开头的文字。感谢str2float() 对整数进行了一次加法(换句话说,1.15 + 2.87 将给出预期结果,4.02,而不是 3.102)。

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

    【讨论】:

    • +1。 甚至可以让它工作(这说明了很多)但是有没有办法保留尾随的零。
    • printf() 可能是? (:h printf()) -> ...\=printf('%.4f', 1.15+str2float(......))
    • 我必须查找的东西:\= 允许替换字符串是一个表达式。 (link)
    • 要添加两个没有尾随小数的整数,请使用str2nr。更多功能见:h functions
    【解决方案2】:

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

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

    (仅没有换行符)。

    【讨论】:

      【解决方案3】:

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

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

      如果您不想在所有行上都这样做,而只想匹配“识别文本”的那一行,则将所有 % 替换为“g/indentifying text/”

      【讨论】:

        【解决方案4】:

        对于整数,您可以使用 n^A 将 n 加到一个数字上(并使用 n^X 减去它)。我怀疑这是否适用于小数。

        【讨论】:

          【解决方案5】:

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

          【讨论】:

          • 大坝!刚刚读到它是一台 Windows 机器,所以忘记 awk :D
          【解决方案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
          

          【讨论】:

          • OP 想要用 1.15 增加一个数字(“a 给定数字”
          猜你喜欢
          • 1970-01-01
          • 2010-12-19
          • 1970-01-01
          • 1970-01-01
          • 2020-09-29
          • 2023-03-23
          • 2014-06-16
          • 2010-11-12
          • 1970-01-01
          相关资源
          最近更新 更多