Alexander Shmatko Alexander Shmatko - 6 months ago 9
Ruby Question

How to save chunk of information between two words to a file?

I have a following file:

old_file

new_file
Some string.
end

Text in the middle that is not supposed to go to any of files.

new_file
Another text.
end


How using regex can I create two files with the following content:

file1

new_file
Some string.
end


file2

new_file
Another text.
end


How can I get information which is between keywords 'new_file' and 'end' to write it to the file?

Answer

If your files are not that large, you can read them in as a string, (use File.read(file_name)), and then run the following regex:

file_contents.scan(/^new_file$.*?^end$/m).select { |block| WRITE_TO_FILE_CODE_HERE }

See the regex demo

The ^new_file$.*?^end$ regex matches new_file that is a whole line content, then 0+ any characters as few as possible (incl. a newline as /m modifier is used), and then end (a whole line).

Else, you may adapt this answer here as

printing = false
File.open(my_file).each_line do |line|
  printing = true if line =~ /^new_file$/      
  puts line if printing
  printing = false if line =~ /^end$/
end

Open the file when the starting line is found, write to it where puts line is in the example above, and close when printing false occurs.