Nippon87
Nippon87

Reputation: 81

Find keyword and iterate through file to find the next keyword

I am searching a file for a specific keyword. From there I want to search the previous lines for an additional keyword. Ex: Search text for "source". Then search the previous 15 lines of text for the keyword "destination". The problem is, the second keyword appears within about a 15-20 line range from the first keyword, so I can't just put lines[i-15] because it won't return the same result for each instance of finding the keyword "source".

I've tried setting a variable that will increment if the second keyword is not found in the line above so that it will keep iterating and searching but it through an error.

First attempt...

   keyword_2 ="destination
   j = 
   if re.match(keyword_1, line):
                lineafter = lines[i + j]
                lineafter_split= lineafter.split(' ')

            if value2 and cell_value in line:
                if 'access-list' not in line:
                    if 'nat' not in line:
                        lineafter_2 = lines[i + 1]
                        if 'description' not in lineafter_2:
                            print(lineafter_2)




Second attempt ...
```keyword_1 ="source"
   keyword_2 ="destination
   j=1
   for i, line in enumerate(lines):
       if keyword_1 in line:
          prev_line=lines[i - j]
           for i in range(1,15):
               if w in prev_line:
                   print(prev_line)
               else:j= j+1

Upvotes: 0

Views: 548

Answers (2)

Born Tbe Wasted
Born Tbe Wasted

Reputation: 610

Okay , so what I understood is that you want to iterate through the text , and then look for the second Keyword prior to that.

However as I am unclear if you want to prevent the search from going too far , or if you want to look for the second keyword until there are no previous lines, I will give you a function that does both.

def looking_for_keywords(lines, keyword_1, keyword_2, range = None):
    for i,line in enumerate(lines):
        if keyword_1 in line:
            j=0
            max = range if range else i
            not_found = True
            while j<max and not_found:
                j+=1 
                not_found = not(keyword_2 in lines[i-j])
            if not_found:
                print('Not Found')
            else:
                print(f'Found first at {i} and second at {i-j}')

Note that your answer does not give the same result ,and will behave weirdly if i <3

Upvotes: 1

Nippon87
Nippon87

Reputation: 81

Looks like I found the answer in case anyone else is having the same issue.

    for i, line in enumerate(lines):
        if keyword_1 in line:
            prev_line=lines[i - 1]
            for k in range(1,3):
                j=k
                prev_line=lines[i - j]
                print(prev_line)
 #Then search for keyword_2

Upvotes: 0

Related Questions