Search code examples
pythontextreplacequotesdouble-quotes

Remove surrounding text using Python


I have created a Python script that replaces text and adds quotes to characters from a text file. I would like to remove any other surrounding lines of text, which usually starts with the word "set".

Here is my current code:

import re

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')

        line = re.sub(r'set interfaces ge-0/0/0 description (.*)', r'interface 1/1\nname "\1"', line)
        line = re.sub(r'set interfaces ge-0/0/1 description (.*)', r'interface 1/2\nname "\1"', line)
#and so on...

fout.write(line)

The source text file contains surrounding text like this:

set system auto-snapshot
set system domain-name EX4300.lab
set system time-zone America/New_York
set system no-redirects
set system internet-options icmpv4-rate-limit packet-rate 2000
set system authentication-order tacplus
set system ports console type vt100

I would like to remove any other text that I have not called for in the code.

I have tried adding this to the bottom of my code with no success:

        for aline in fin:
           new_data = aline
        if new_data.startswith("set"):
            new_data = ""

Solution

  • What I would do is read the file, create a string with all of the info, then write it to a different file. It would go something like this:

    import re
    
    with open("SanitizedFinal_E4300.txt", "r") as f:
        read = f.read()
    
    info = ""
    for line in read.split("\n"):
        og_line = line
        
        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')
        line = re.sub(r'set interfaces ge-0/0/0 description (.*)', r'interface 1/1\nname "\1"', line)
        line = re.sub(r'set interfaces ge-0/0/1 description (.*)', r'interface 1/2\nname "\1"', line)
            
        if "set" in line and line == og_line: # line == og_line makes sure that "line" wasn't changed at all
            line = ""
    
        if line != "":
            info += line + "\n"
    
    with open("output6.txt", "w+") as f:
        f.write(info)