【问题标题】:Efficiently replacing text in a file between two lines matching a pattern在匹配模式的两行之间有效替换文件中的文本
【发布时间】:2019-10-02 22:09:54
【问题描述】:

我想在第一次出现标题后在 python 中编辑一个很长的文件。该文件如下所示:

*First Heading
line1
line2
line3
line4
*Second Heading
line1
line2
line3
line4
*Third Heading 
line1
line2
line3
...
...
more headings and many more lines

我想替换(例如)第二个标题的 line2,如下所示:

someNewtext line2

我可以使用 sed 非常有效地做到这一点:

sed -e -i '/\*Second\ Heading/,/\*Third\ Heading/s/line2/someNewText\ line2/' file.txt 

我可以在 Python 中高效地做类似的事情吗?

【问题讨论】:

  • python或者高效你要选一个

标签: python sed


【解决方案1】:

使用subprocess module,您可以像以前一样使用sed。

subprocess.run("sed -e -i '/\*Second\ Heading/,/\*Third\ Heading/s/line2/someNewText\ line2/' file.txt")

【讨论】:

    【解决方案2】:

    如果我们要将sed 命令移植到python,它将如下所示:

    import re
    import fileinput
    
    state = 0
    for line in fileinput.input('file.txt', inplace=True, backup='.bak'):
        line = line.rstrip('\r\n')
        if state == 1:
            line = re.sub('line2', 'someNewText line2', line)
        if line.startswith('*Second Heading'):
            state = 1
        elif line.startswith('*Third Heading'):
            state = 0
        print line
    fileinput.close()
    

    它在执行时间上会很高效,但可能效率不高 编程为sedPerl。叹息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-10
      • 1970-01-01
      • 2014-10-24
      • 1970-01-01
      • 1970-01-01
      • 2013-06-17
      • 2023-01-18
      • 1970-01-01
      相关资源
      最近更新 更多