[英]How to parse and print a matching search in a line of text, plus the next 2 lines after a match in Python
下面的代码非常适合匹配和打印出单个匹配行,但我还需要查看 Cisco 配置文件中下一行的数据。
fopen = open('running-config.cfg',mode='r+')
fread = fopen.readlines()
x = input("Enter the search string: ")
for line in fread:
if x in line:
print(line)
如果在下面的示例中我的搜索是“服务器”,我如何在上面的代码中打印下一行是“主机 10.3.59.119”。 如果我能同时拥有两条线,这将是巨大的。
object network server
host 10.3.59.119
我会在 for 循环之外添加一个计数器,将其设置为零。 如果找到匹配项,请将其设置为两个。 现在添加一个 if 语句来检查计数器是否 > 0。如果是,则打印该行并减少计数器。
就像是:
counter = 0
for line in fread:
if x in line:
print(line)
counter = 2
elif counter > 0: # elif because otherwise the line would be printed twice
print(line)
counter -= 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.