Skip to content

Instantly share code, notes, and snippets.

@mallowlabs
Created March 3, 2015 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mallowlabs/7d07d29c796172c214a5 to your computer and use it in GitHub Desktop.
Save mallowlabs/7d07d29c796172c214a5 to your computer and use it in GitHub Desktop.
A multiline grep.
class MultiGrep
def usage
puts "Example: ruby multi_grep.rb base.php:10-20 search/*.php"
end
def grep(argv = ARGV)
base = argv.first
path, range = base.split(":")
s, e = range.split("-").map { |i| i.to_i }
File.open(path) do |f|
base_lines = f.readlines[s-1..e-1].map { |line| line.rstrip }
base_line = base_lines.first
array_size = base_lines.size
argv[1..-1].each do |path|
File.open(path) do |f|
lines = f.readlines.map { |line| line.rstrip }
lines.each_with_index do |line, i|
if line == base_line && match(lines, base_lines, i, i + array_size - 1)
puts "#{path}:#{i+1}-#{i+array_size}"
end
end
end
end
end
end
private
def match(lines, base_lines, start_index, end_index)
base_lines == lines[start_index..end_index]
end
end
if __FILE__ == $0
if ARGV.first =~ /(.+):[\d]+-[\d]+/
MultiGrep.new.grep
else
MultiGrep.new.usage
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment