Python Forum
[SOLVED] Find last occurence of pattern in text file?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[SOLVED] Find last occurence of pattern in text file?
#5
It's just a ~100KB file, so it fast enough.

I simplified the script with a function:

import re
#pip install pyperclip
import pyperclip

def SearchAndTell(MYFILE,mypattern):
	p = re.compile(mypattern)
	for line in reversed(open(MYFILE).readlines()):
		m = p.search(line.rstrip())
		if m:
			return m.group(1)
			break #needed?

INPUTFILE = "log.txt" 
clipb = None

pattern = "^START_A.+to (.+?) \(.+$"
clipb = f"-ss {SearchAndTell(INPUTFILE,pattern)} ".replace(",",".")
pattern = "^START_B.+to (.+?) \(.+$"
clipb += f"-to {SearchAndTell(INPUTFILE,pattern)}".replace(",",".")

pyperclip.copy(clipb)
FWIW, here's the batch script:
grep -Poha "^START_A.+$" log.txt | sed -r "s@^.+ to (.+?) \(.+$@-ss \1@" | sed -r "s@,@.@g" | tail -1
grep -Poha "^START_B.+$" log.txt | sed -r "s@^.+ to (.+?) \(.+$@-to \1@" | sed -r "s@,@.@g" | tail -1
Reply


Messages In This Thread
RE: Find last occurence of pattern in text file? - by Winfried - Aug-13-2021, 08:21 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
Question [SOLVED] Correct way to convert file from cp-1252 to utf-8? Winfried 8 895 Feb-29-2024, 12:30 AM
Last Post: Winfried
  FileNotFoundError: [WinError 2] The system cannot find the file specified NewBiee 2 1,591 Jul-31-2023, 11:42 AM
Last Post: deanhystad
  Loop through json file and reset values [SOLVED] AlphaInc 2 2,148 Apr-06-2023, 11:15 AM
Last Post: AlphaInc
  Cannot find py credentials file standenman 5 1,662 Feb-25-2023, 08:30 PM
Last Post: Jeff900
  selenium can't find a file in my desk ? SouAmego22 0 751 Feb-14-2023, 03:21 PM
Last Post: SouAmego22
  Pypdf2 will not find text standenman 2 947 Feb-03-2023, 10:52 PM
Last Post: standenman
Thumbs Up Need to compare the Excel file name with a directory text file. veeran1991 1 1,132 Dec-15-2022, 04:32 PM
Last Post: Larz60+
  Find (each) element from a list in a file tester_V 3 1,236 Nov-15-2022, 08:40 PM
Last Post: tester_V
  [SOLVED] [Beautifulsoup] Find if element exists, and edit/append? Winfried 2 4,315 Sep-03-2022, 10:14 PM
Last Post: Winfried
  [Solved by deanhystad] Create a zip file using zipfile library DZ_Galaxy 2 1,172 Aug-17-2022, 04:57 PM
Last Post: DZ_Galaxy

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020