Reilly Aiden
Reilly Aiden

Reputation: 3

Python - Printing A Specific Part Of A Config Line

I'm having trouble copying information from a config file for switches I work with. When I run the below script it gives me a full line of, 'Switchport Access Vlan 99' for example. The problem is that I just want/need it to return 'Vlan 99'. Any suggestions?

input_file = open('X:\\abc\\def\\ghi.txt', 'r')
output_file = open('X:\\abc\\def\\jkl.txt', 'w')
for line in input_file:
    if "vlan" in line:
        print(line)
        output_file.write(line)

Upvotes: 0

Views: 47

Answers (2)

camz
camz

Reputation: 605

Depending on the contents of the files you may have to do something different.

If each like is "Some random text Vlan 99" then you could use:

for line in input_file:
  if "vlan" in line:
    s = line[line.find("Vlan"):]
    print(s)
    output_file.write(s)

line.find("text") return the index of the string if found, -1 otherwise. line[N:] returns the substring from an index to the end.

For another way of getting the substring out you could look into line.split() and then take the last element of that list to get your number.

Upvotes: 0

Johan
Johan

Reputation: 1693

Given that all the lines starts with 'Switchport Access' you can just use the string method replace

line = "Switchport Access Vlan 99"
interesting_part = line.replace("Switchport Access ", "")

Upvotes: 1

Related Questions