繁体   English   中英

Python 匹配后用换行符替换单词

[英]Python replace word with newline after a match

我正在使用 python 3.6,我有一个看起来像这样的文件:

    interface Ethernet94
    profile users-1
    !
    interface Ethernet95
    profile users-admin
    !
    interface Ethernet96
    profile users-reg
    !

我希望可以选择根据上面一行的接口号替换“profile”之后的单词。

因此,要将interface Ethernet96profile users-reg更改为profile users-all ,我已经尝试过:

    #!/usr/bin/env python3
    import sys
    import fileinput
    filename = '/root/test'
    for line in fileinput.input([filename], inplace=True):
        if line.strip().startswith('interface Ethernet96\nprofile'):
            line = 'interface Ethernet96\nprofile users-all'
        sys.stdout.write(line)

但这对文件没有任何作用。 我找不到解决方案,因为所有示例都显示了如何逐字替换。 但是我不能根据名称更改配置文件,因为我可以有多个具有相同配置文件的接口。

请协助!

regex会做得很好

from pathlib import Path
import re

file = Path("file.txt")
content = file.read_text()
content = re.sub(r"(interface Ethernet96\nprofile) ([-\w]+)", r"\1 users-all", content)
file.write_text(content)

使用Ethernet96行的索引替换该行

from pathlib import Path

file = Path("file.txt")
content = file.read_text().splitlines()

row_idx = content.index("interface Ethernet96")
content[row_idx + 1] = "profile users-all"

暂无
暂无

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

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