简体   繁体   中英

Go to next lines when reading a file in Ruby

I'm reading a file line by line. When I find a specific string I would like to analyze the following lines until a specific character is present. In concrete. This is my input file:

 blabbal
 blabbalb
 blablab
 info {
     (bbbbb,
     ccccc,
     dddddddddd,
     eeeeeeeeeeeeeee
     fffffffffffffff);
     xxxxxxxxxxxxxxx, 
     rrrrrrrrrrrrrrr,
     };
 blabbal

I'm reading the file using

  File.open("example.txt", "r").each_line do |line|

Then I would like that: 1) when I find the string "info" iterate within a while loop the next lines until I find the characters ");"

This is an example of my current code:

        File.open("example.txt", "r").each_line do |line|
            if (line.include?("info") == true)
                while(1) do
                    puts line
                    next if line.include?(")") == false
                end
            end
        end

It seems that it doesn't go to the next line ("puts" prints always the same line -> "info {")

File.open("temp", "r") do |fh|
      while(line = fh.gets) != nil
        if line.include?("info")
          while(line = fh.gets) != nil
            puts "#{line}"
            break if line.include?(")")
          end
        end
      end
    end

I think this is what you need. Its Output is

(bbbbb,
 ccccc,
 dddddddddd,
 eeeeeeeeeeeeeee
 fffffffffffffff);
flag = false
File.new("example.txt").each_line do |line|
  flag = true if line.include?("info")
  puts line if flag
  flag = false if line.include?(")")
end

result:

 info {
     (bbbbb,
     ccccc,
     dddddddddd,
     eeeeeeeeeeeeeee
     fffffffffffffff);
while(1) do
   puts line
   next if line.include?(")") == true
end

will just loop infinitely. next here is bound to the context of the while(1) loop, so of course you are never going to reach the next line of input.

You need to read the lines of the file into some sort of storage, and then process that storage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM