简体   繁体   中英

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?

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      

If they are always three-line chunks separated by one blank line, you could just use the split(1) utility:

split -l 4 old_file

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