Python replace word with newline after a match

Viewed 43

I'm using python 3.6, and I have a file that looks like this:

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

I want to have the option to replace the word that comes after 'profile' based on the interface number on the line above it.

So to change interface Ethernet96 from profile users-reg to profile users-all, I have tried this:

    #!/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)

But this doesn't do anything to the file. I couldn't find a solution as all examples show how to replace word for word. But I cannot change the profile based on its name because I can have multiple interfaces with the same profile.

Please assist!

1 Answers

A regex would do it nice

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)

Replace the line using the indice of the Ethernet96 row

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"
Related