简体   繁体   English

如何解析和打印一行文本中的匹配搜索,以及 Python 中匹配后的下 2 行

[英]How to parse and print a matching search in a line of text, plus the next 2 lines after a match in Python

the Code below works great for matching and printing out a single matching line, but I also need to see the data on the next line in a Cisco configuration file.下面的代码非常适合匹配和打印出单个匹配行,但我还需要查看 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)

If my search is "server" in the example below, how do I print the next line in the code above which is "host 10.3.59.119".如果在下面的示例中我的搜索是“服务器”,我如何在上面的代码中打印下一行是“主机 10.3.59.119”。 If I could have both lines, this would be huge.如果我能同时拥有两条线,这将是巨大的。

object network server
 host 10.3.59.119

I would add a counter outside the for loop setting it to zero.我会在 for 循环之外添加一个计数器,将其设置为零。 If there is a match found set it to two.如果找到匹配项,请将其设置为两个。 Now add an if statement which checks if counter > 0. If so print the line and decrease the counter.现在添加一个 if 语句来检查计数器是否 > 0。如果是,则打印该行并减少计数器。

Something like:就像是:

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.

相关问题 如何使用python在正则表达式搜索后打印下一行 - How to print next line after regex search using python 逐行搜索正则表达式,并在匹配后打印多行 - search regex line by line and print multiple lines after match 模式匹配后打印行,直到下一个模式匹配Python - Print lines after a pattern match until next pattern match Python 在python中匹配文本后打印第N行 - Print a Nth line after matching text in python 如何在与python匹配后打印行? - How to print lines after a match with python? 匹配在python中找到的字符串之后打印一些前面的行 - Print a number of previous lines after matching string found in line in python Python正则表达式搜索行以冒号结尾,所有文本以冒号结尾,直到下一行结尾 - Python regex search lines that end with a colon and all text after until next line that ends with colon Python:如何检查文本文件,将其与另一个文本文件中的每一行进行比较,并打印不匹配的行 - Python: How to check a text file, compare it to each line in another text file, and print the lines that do not match Python文件搜索行并在匹配后返回特定的行数 - Python File Search Line And Return Specific Number of Lines after Match 如何解析python中某个文本后的行 - How to parse lines after a certain text in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM