Created
August 22, 2012 02:30
-
-
Save sue445/3421641 to your computer and use it in GitHub Desktop.
空行で区切られた要素に対してgrepする
This file contains 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
#!/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