Reputation: 123
I bet it's an easy answer for fellow pythoners. I'm a rookie and I've been searching for an answer for quite a while now (hours)...
How to return all lines after last regex match (including and excluding match)? I'm playing with python 2.6
data:
string log 1
string log 2
string match
string log 4
string match
string log 5
string log 6
expected case 1:
string match
string log 5
string log 6
expected case 2:
string log 5
string log 6
Same question for bash what posted here How to get all lines after a line number
sed solution:
sed -n 'H; /string match/h; ${g;p;}'
sed -n 'H; /string match/h; ${g;p;}' | grep -v 'string match'
Upvotes: 0
Views: 5216
Reputation: 71598
If you're looking into a shorter piece of code, maybe that?
Case 1:
>>> import re
>>> input_data = open('path/file').read()
>>> result = re.search(r'.*(string match\s*.*)$', input_data, re.DOTALL)
>>> print(result.group(1))
string match
string log 5
string log 6
Case 2:
>>> import re
>>> input_data = open('path/file').read()
>>> result = re.search(r'.*string match\s*(.*)$', input_data, re.DOTALL)
>>> print(result.group(1))
string log 5
string log 6
Warning though, there'll be a lot of backtracking in that regex if the last 'string match' is way up in the file.
Upvotes: 1
Reputation: 27585
t = '''string log 1
string log 2
string match
string log 4
string match
string log 5
string log 6'''
me = t.rsplit('string match',1)[1].lstrip()
e = t[t.rfind('string match'):]
print '%s\n\n%r\n\n%r' % (t,me,e)
result
string log 1
string log 2
string match
string log 4
string match
string log 5
string log 6
'string log 5\nstring log 6'
'string match\nstring log 5\nstring log 6'
Upvotes: 0
Reputation: 369494
import sys
with open('/path/to/file', 'rb') as f:
last_pos = pos = 0
for line in f:
pos += len(line)
if 'string match' in line:
last_pos = pos
f.seek(last_pos)
sys.stdout.writelines(f)
Used a loop to find last match position. Then used file.seek to move file position.
Upvotes: 0