Last active
October 3, 2018 11:01
-
-
Save bbtdev/33ca0645ea395cdfbe6601314e501745 to your computer and use it in GitHub Desktop.
ruby read file from bottom to top until match
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # thank you aperios from #ruby | |
| #! /usr/bin/env ruby | |
| class Rubash | |
| def tail_match(filename, pattern) | |
| fd = File.open(filename, 'rb') | |
| file_byte_size = fd.size | |
| pos = 0 | |
| result = '' | |
| result.encode!(Encoding::BINARY) | |
| match = 0 | |
| while (file_byte_size > -pos) && match.zero? do | |
| pos -= 1 | |
| fd.seek(pos, IO::SEEK_END) | |
| result = fd.read(1) + result | |
| match = 1 if result[0..2] == pattern | |
| end | |
| return '' if match.zero? | |
| result | |
| end | |
| end | |
| puts Rubash.new.tail_match('test.txt', '---') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment