0

I apologize if I didn't ask this question properly. It was kind of confusing. But for a visual example if I have this txt file:

| $100 on the first line
| $654 on the second line
| $123 on the third line
| $111 on the fourth line

How could I find the last time $ was used to print out 111?

WaddyBox
  • 63
  • 2
  • 8
  • How large does the text file get? Would it fit in memory? What have you tried yourself? Please share your code and the problems you had with it. – Grismar Jan 15 '21 at 04:55

3 Answers3

0

You can use str.rfind() to get the last instance of a string (reversed first find) and then use that to index the string.

import io

file = "| $100 on the first line\n| $654 on the second line\n| $123 on the third line\n| $111 on the fourth line"
txt = io.StringIO(file).getvalue()

idx = txt.rfind('$')

#txt[idx+1:idx+4]
txt[idx+1:].split()[0]  #takes the complete first token instead of 3 characters
'111'
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
0

Well, depending of your needs bash may be more efficient for this. from your shell command line:

$ grep "$" file.txt | cut -d "$" -f2 | cut -d " " -f1 | tail -1

Output:

111
Synthase
  • 5,849
  • 2
  • 12
  • 34
-1

for small files see this: How to read a file in reverse order?

for large files such that you need to consider diskIO, maybe try to seek() to end of file and read back (in chunks)

Bing Wang
  • 1,548
  • 1
  • 8
  • 7