Skip to content

Instantly share code, notes, and snippets.

@bbtdev
Last active October 3, 2018 11:01
Show Gist options
  • Select an option

  • Save bbtdev/33ca0645ea395cdfbe6601314e501745 to your computer and use it in GitHub Desktop.

Select an option

Save bbtdev/33ca0645ea395cdfbe6601314e501745 to your computer and use it in GitHub Desktop.
ruby read file from bottom to top until match
# 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