Home > Mobile >  How to print a first line having a specific string after last occurrence of another string?
How to print a first line having a specific string after last occurrence of another string?

Time:12-08

I have a file named file.txt

file.txt

this is first line
this is second line 
new( line added )
this is second line
this is fourth line
new( line three added)
this is fourth line_1
this is fifth line_three
this is fourth line_1
this is fourth line_5


from this file i need to print line That have string "fourth" after the last occurrence of string "new("

Expected output:

this is fourth line_1

This is current attempt:

fin = open("file.txt", "r")
for line in reversed(fin.readlines()):
    if 'new(' in line:
        
        

this will go to last line that have string new( in it. Now i need to check the first occurrence of string fourth after that last new( and print that line. How can i do this?

CodePudding user response:

Read 2 lines at once and check 2 conditions at once.

lines = open('file.txt').readlines()
for item, next_item in zip(lines, lines[1:]):

    if 'new(' in item and 'fourth' in  next_item:

        print(next_item)
    

Gives #

this is fourth line_1

CodePudding user response:

This is what I came up with

from typing import Optional

with open("test.txt", "r") as file:
    lines = file.readlines()

line_new_index: Optional[int] = None
line_fourth_index: Optional[int] = None

for index, line in enumerate(lines):
    if "new(" in line:
        line_new_index = index
        line_fourth_index = None
    if "fourth" in line and line_new_index is not None and line_fourth_index is None:
        line_fourth_index = index

print(lines[line_fourth_index])

This effectively prints this is fourth line_1 with the file you provided

  • Related