Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Certain Lines from File

Tags:

ruby

Hi just getting into Ruby, and I am trying to learn some basic file reading commands, and I haven't found any solid sources yet.

I am trying to go through certain lines from that file, til the end of the file.

So in the file where it says FILE_SOURCES I want to read all the sources til end of file, and place them in a file.

I found printing the whole file, and replacing words in the file, but I just want to read certain parts in the file.

like image 240
Ryn Avatar asked Aug 10 '26 14:08

Ryn


1 Answers

Usually you follow a pattern like this if you're trying to extract a section from a file that's delimited somehow:

open(filename) do |f|
  state = nil

  while (line = f.gets)
    case (state)
    when nil
      # Look for the line beginning with "FILE_SOURCES"
      if (line.match(/^FILE_SOURCES/))
        state = :sources
      end
    when :sources
      # Stop printing if you hit something starting with "END"
      if (line.match(/^END/))
        state = nil
      else
        print line
      end
    end
  end
end

You can change from one state to another depending on what part of the file you're in.

like image 98
tadman Avatar answered Aug 13 '26 05:08

tadman