【问题标题】:How to replace a number in a text file using regular expressions如何使用正则表达式替换文本文件中的数字
【发布时间】:2022-11-17 20:22:59
【问题描述】:

我有一个包含很多行的文本文档,看起来像这样:

some_string_of_changing_length 1234.56000000 99997.65723122992939764 4.63700 text -d NAME -r

我想逐行更改第 4 个条目(本例中的数字 4.63700)并将其替换为另一个数字。

我想我必须使用正则表达式,但我不确定如何要求仅替换第 4 个条目。

我很乐意在 python 或 bash 中执行此操作——无论哪种最简单。

【问题讨论】:

    标签: python bash


    【解决方案1】:

    如果您知道偏移量 - 以下将对您有用(因此不需要正则表达式)

    line = 'some_string_of_changing_length 1234.56000000 99997.65723122992939764 4.63700 text -d NAME -r'
    new_val = 'I am the new val'
    parts = line.split(' ')
    parts[3] = new_val
    line = ' '.join(parts)
    print(line)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-16
      • 2017-10-18
      • 2014-03-11
      • 1970-01-01
      • 2020-04-03
      • 2017-06-17
      相关资源
      最近更新 更多