Aug-13-2021, 04:41 PM
tail doesn't select on patterns or show the "the last occurrence" of something, so I'm not sure I understand what you're looking for.
Do you have to support patterns (just a string match is insufficient)? Can the pattern span lines, or will it always be in a single line? Do you want to display the entire line the pattern matches, or just the result of the match?
Your first one looks like you have a slow pattern. It's possible to construct a pattern that requires backtracking. If you require pattern support across the entire file, it will be possible to supply a pattern that is slow. But if the pattern only has to match within a line, that will usually limit the problems that can arise.
If you don't need full pattern support, and you want to see the line of last occurrence, I'd probably suggest something like:
Do you have to support patterns (just a string match is insufficient)? Can the pattern span lines, or will it always be in a single line? Do you want to display the entire line the pattern matches, or just the result of the match?
Your first one looks like you have a slow pattern. It's possible to construct a pattern that requires backtracking. If you require pattern support across the entire file, it will be possible to supply a pattern that is slow. But if the pattern only has to match within a line, that will usually limit the problems that can arise.
If you don't need full pattern support, and you want to see the line of last occurrence, I'd probably suggest something like:
INPUTFILE = "log.txt" target = "print" with open(INPUTFILE) as reader: last_line = None for line in reader.read().splitlines(): if target in line: last_line = line if last_line: print(last_line) else: print("No match")