Ruby:在多个目录中的多个文件中搜索正则表达式

时间:2021-01-24 22:10:27

Please forgive my ignorance, I am new to Ruby.

请原谅我的无知,我是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.

我无法弄清楚如何对多个文件和目录使用我的正则表达式。任何和所有的帮助非常感谢。

1 个解决方案

#1


5  

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

嗯,你很亲密。首先使模式成为Regexp对象:

pattern = /hello/

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

或者,如果您尝试从String创建Regexp(如在命令行中传入),您可以尝试:

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.

现在,当您搜索时,line是一个String。您可以使用匹配或扫描来获得与您的模式匹配的结果。

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

#1


5  

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

嗯,你很亲密。首先使模式成为Regexp对象:

pattern = /hello/

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

或者,如果您尝试从String创建Regexp(如在命令行中传入),您可以尝试:

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.

现在,当您搜索时,line是一个String。您可以使用匹配或扫描来获得与您的模式匹配的结果。

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