Search code examples
ruby-on-railsrubyrake

Find a specific text segment within a file and than search for specific line in ruby


I'm trying to find a specific text segment within a text file and than a specific line within the text segment. The algorithm should be as follow:

1)First, search for a line which contains the keyword "Macros"

2)The next found line must contain the keyword "Name"

3)And finally print me the next line

As pseudo code I mean something like this:

File.open(file_name) do |f|
  f.each_line {|line|
    if line.include?("Macros")
      and if next line.include?("Name")
        print me the line after
    end

Any suggestions?


Solution

  • I would use boolean flags to remember that I already matched the parts of the condition:

    File.open(file_name) do |file|
      marcos_found = false
      name_found   = false
    
      file.each_line do |line|
        if line.include?('Macros')
          marcos_found = true 
    
        elsif found_marcos && line.include?("Name")
          name_found = true
    
        elsif marcos_found && name_found
          puts line
          break # do not search further or print later matches
        end
      end
    end