Alexander Shmatko Alexander Shmatko - 6 months ago 10
Ruby Question

How to read content of a file and then split the content into several files?

Suppose, I have a file with the following text:

old_file

create_table "users", force: :cascade do |t|
t.string "name"
end

create_table "animals", force: :cascade do |t|
t.string "kind"
end


I need to split this file so that every create_table block would be created on different files. For instance:

file1

create_table "users", force: :cascade do |t|
t.string "name"
end


file2

create_table "animals", force: :cascade do |t|
t.string "kind"
end


I can read the file and than assign it to some variable,

string = File.open('old_file', 'r'){ |file| file.read }


but I can't wrap my head around what I am supposed to do next.

Maybe I could use regex to identify each time new 'create_table' title and then somehow create new file, write content to there and close the file 'till next 'create_table' occurrence.

How would you do this?

Answer

Here is a ruby solution:

index = 0                                                                                                                                                                                                                                
IO.foreach("old_file.rb") do |line|                                                                                                                                                                                                      
  index += 1 if line =~ /^create_table/                                                                                                                                                                                                  
  File.open("file#{index}", 'a') do |f|                                                                                                                                                                                                  
    f.write(line)                                                                                                                                                                                                                        
  end                                                                                                                                                                                                                                    
end