Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Searching a regular expression across multiple files in multiple directories

Tags:

regex

ruby

Please forgive my ignorance, I am new to Ruby.

I know how to search a string, or even a single file with a regular expression:

str = File.read('example.txt')
match = str.scan(/[0-9A-Za-z]{8,8}/)

puts match[1]

I know how to search for a static phrase in multiple files and directories

pattern = "hello"

Dir.glob('/home/bob/**/*').each do |file|
    next unless File.file?(file)
        File.open(file) do |f|
            f.each_line do |line|
                puts "#{pattern}" if line.include?(pattern)
        end
    end
end

I can not figure out how to use my regexp against multiple files and directories. Any and all help is much appreciated.

like image 581
roobnoob Avatar asked Feb 13 '11 05:02

roobnoob


1 Answers

Well, you're quite close. First make pattern a Regexp object:

pattern = /hello/

Or if you are trying to make a Regexp from a String (like passed in on the command line), you might try:

pattern = Regexp.new("hello")
# or use first argument for regexp
pattern = Regexp.new(ARGV[0])

Now when you are searching, line is a String. You can use match or scan to get the results of it matching against your pattern.

f.each_line do |line|
  if line.match(pattern)
    puts $0
  end
  # or
  if !(match_data = line.match(pattern)).nil?
    puts match_data[0]
  end
  # or to see multiple matches
  unless (matches = line.scan(pattern)).empty?
    p matches
  end
end
like image 128
wuputah Avatar answered Nov 11 '22 14:11

wuputah