I have been struggling with a text file to perform conditional appending/extending certain text using Python. My apologies in advance if this is too basic and already been discussed here in someway or the other :(
Concerning the code (attached), I need to add statement "mtu 1546" under the statement containing "description" only if it doesn't exist. Also, I would like to be able add "description TEST" statement under interface statement (and/or above mtu statement, if available) only if doesn't pre-exist. I am using python 2.7.
Here's is my code:
import re
f = open('/TESTFOLDER/TEST.txt','r')
interfaces=re.findall(r'(^interface Vlan[\d+].*\n.+?\n!)',f.read(),re.DOTALL|re.MULTILINE)
for i in interfaces:
interfaceslist = i.split("!")
for i in interfaceslist:
if "mtu" not in i:
print i
f.close()
print statement works fine with the condition as it's able to print the interesting lines correctly, however my requirement is to add (append/extend) the required statements to the list so I can further use it for parsing and stuff. Upon, trying append/extend function, the interpreter complains it to be a string object instead. Here's the sample source file(text). The text files I will parsing from are huge in size so only adding the interesting text.
!
interface Vlan2268
description SNMA_Lovetch_mgmt
mtu 1546
no ip address
xconnect 22.93.94.56 2268 encapsulation mpls
!
interface Vlan2269
description SNMA_Targoviste_mgmt
mtu 1546
no ip address
xconnect 22.93.94.90 2269 encapsulation mpls
!
interface Vlan2272
mtu 1546
no ip address
xconnect 22.93.94.72 2272 encapsulation mpls
!
interface Vlan2282
description SNMA_Ruse_mgmt
no ip address
xconnect 22.93.94.38 2282 encapsulation mpls
!
interface Vlan2284
mtu 1546
no ip address
xconnect vfi SNMA_Razgrad_mgmt
!
interface Vlan2286
description mgmt_SNMA_Rs
no ip address
xconnect 22.93.94.86 2286 encapsulation mpls
!
interface Vlan2292
description SNMA_Vraca_mgmt
mtu 1546
no ip address
xconnect 22.93.94.60 2292 encapsulation mpls
!
iin the outer loop after finishing the inner loop, its value would have been the last element ofinterfaceslist.