0

I am attempting to replace text from a source file into a new file. The replacing of text works for one line, but a few lines down and I fail to replace text sitting in the middle of a statement.

Here is the source text. The words in brackets are what I am trying to replace, without changing the characters around the words:

[set interfaces] ge-0/0/0 [description] "OoB Mgmt Connection"

This is what I would like to output:

interface x/x name "xxx" (also adding quotations for the xxx text after "name")

However the output text replaces once, and then keeps three copies of the original text:

    hostname "EX4300"
    set system host-name EX4300
    set system host-name EX4300
    set system auto-snapshot
    set system auto-snapshot
    set system auto-snapshot 

Here is my code:

    with open("SanitizedFinal_E4300.txt", "rt") as fin:
         with open("output6.txt", "wt") as fout:
              for line in fin:
                  fout.write(line.replace('set system host-name EX4300', 'hostname "EX4300"'))
                  fout.write(line.replace('set interfaces ge-0/0/0 unit 0 family inet address', 'ip address'))

Please let me know where I went wrong or if there is a better way of approaching this. I am using Visual Studio Code.

2
  • It is unclear to me what you're trying to do. Can you give a complete source text, and a complete desired output? Commented Jan 18, 2022 at 21:08
  • just like your previous version of this question, it is still unclear what you want to search and replace Commented Jan 18, 2022 at 22:45

1 Answer 1

1

Only use 1 fout.write(), call the replace function al often as you want.

with open("SanitizedFinal_E4300.txt", "rt") as fin:
    with open("output6.txt", "wt") as fout:
        for line in fin:
            line = line.replace('set system host-name EX4300', 'hostname "EX4300"')
            line = line.replace('set interfaces ge-0/0/0 unit 0 family inet address', 'ip address')
            fout.write(line)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.