我正在检查文本文件中的命令块,如下所示-
File start -
!
interface Vlan100
description XYZ
ip vrf forwarding XYZ
ip address 10.208.56.62 255.255.255.192
!
interface Vlan101
description ABC
ip vrf forwarding ABC
ip address 10.208.55.126 255.255.255.192
no ip redirects
no ip unreachables
no ip proxy-arp
!
File End我想要创建一个txt文件,如果在源文件中我得到一个模式vrf转发ABC输出应该是接口Vlan101
到目前为止,我所做的是跟随脚本,但它只显示了包含模式的行。
import re
f = open("output_file.txt","w") #output file to be generated
shakes = open("input_file.txt","r") #input file to read
for lines in shakes:
if re.match("(.*)ABC(.*)",lines):
f.write(lines)
f.close()发布于 2018-01-12 07:27:43
最简单的:读取文件,剪切!所在的位置,然后对每个文件,如果有所需的文本,则获取第一行:
with open("input_file.txt") as r, open("output_file.txt", "w") as w:
txt = r.read()
result = [block.strip().split("\n")[0]
for block in txt.split('!')
if 'vrf forwarding ABC' in block]
w.write("\n".join(result))发布于 2018-01-12 07:36:08
为了明确起见,我想您希望用"vrf转发ABC“替换”接口Vlan101“的任何实例。在本例中,我将test.txt作为输入文件,out.txt作为输出文件,并根据需要使用所有替换的实例。我使用了一个列表理解--使用一个列表字符串方法--将“接口Vlan101”的子字符串替换为"vrf转发ABC“。
with open("test.txt") as f:
lines = f.readlines()
new_lines = [line.replace("interface Vlan101", "vrf forwarding ABC" for line in lines]
with open("out.txt", "w") as f1:
f1.writelines(new_lines)希望这能有所帮助。
发布于 2018-01-12 07:42:53
如果您只是对接口感兴趣,您也可以这样做。
#Read File
with open('sample.txt', 'r') as f:
lines = f.readlines()
#Capture 'interfaces'
interfaces = [i for i in lines if i.strip().startswith('inter')]
#Write it to a file
with open('output.txt', 'w') as f:
f.writelines(interfaces)https://stackoverflow.com/questions/48221338
复制相似问题