简体   繁体   中英

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.

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". 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM