Skip to content

Instantly share code, notes, and snippets.

@sue445
Created August 22, 2012 02:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sue445/3421641 to your computer and use it in GitHub Desktop.
Save sue445/3421641 to your computer and use it in GitHub Desktop.
空行で区切られた要素に対してgrepする
#!/usr/bin/env ruby
# -*- encoding: utf-8 -*-
=begin
空行で区切られた要素に対してgrepする
=end
if ARGV.length < 2
puts "<usage> ruby multiline_grep.rb [search_file] [search_text1] [search_text2] ..."
exit
end
class String
# substrsの中身を全て含んでいるかどうか
def all_include?(substrs)
substrs.each do|str|
return false unless self.include? str
end
true
end
end
search_file = ARGV[0]
$search_texts = ARGV.clone
$search_texts.shift
$count = 0
def check_all_include(str)
if str.all_include?($search_texts)
$count += 1
puts str
puts ""
end
end
File.open(search_file) do |file|
line_buffer = ""
while line = file.gets
if line.strip.length == 0
check_all_include(line_buffer)
line_buffer.clear
else
line_buffer += line
end
end
if line_buffer.length > 0
check_all_include(line_buffer)
end
end
puts "hit count = #{$count}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment