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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With