Problem I have is that I want to insert text in a text file after a
specific line.
My thought was to copy the original file line by line and when I got to
a specific line it would insert the text that I wanted, but I did not
manage to do this so I went another way, like this
File.open('test.bak', 'r+') do |file|
file.each do |line|
if line =~ /\<\/DHCPServer>/ #trigger
file.seek(-line.size, IO::SEEK_CUR)
file.puts ("Hello") #text to input
end
end
end
But when I use this, first it manipulates the original file and it
deletes some of the letter of the trigger "</DHCPServer>"
Problem I have is that I want to insert text in a text file after a
specific line.
My thought was to copy the original file line by line and when I got to
a specific line it would insert the text that I wanted
This sounds like the approach that I would use. Open a source file to read, open the destination file. Read it in a line at a time, write it out. Make changes as you go, adding lines, removing them, etc. At EOF, close both files. Remove the old source and replace with the destination if desired. A Variation includes holding the whole new file in memory and writing it out in one step at the end.
, but I did not
manage to do this
Do you have your attempt at this to share? Someone might be able to spot the problem if you post it.
so I went another way, like this
File.open('test.bak', 'r+') do |file|
file.each do |line|
if line =~ /\<\/DHCPServer>/ #trigger
file.seek(-line.size, IO::SEEK_CUR)
file.puts ("Hello") #text to input
end
end
end
But when I use this, first it manipulates the original file and it
deletes some of the letter of the trigger "</DHCPServer>"
Does anyone have a solution on how to either see the problems with the
above code or a solution on how to do it with reading line by line and
inserting the text after a specific line?
File.open("destination.txt", "w") do |out|
File.foreach("original.txt") do |line|
out.puts line
if line =~ /YOUR_REGEX/
out.puts "THE NEW LINE"
end
end
end
Jesus.
···
On Mon, Apr 16, 2012 at 9:09 PM, fox foxmaster <lists@ruby-forum.com> wrote:
Hi all,
Does anyone have a solution on how to either see the problems with the
above code or a solution on how to do it with reading line by line and
inserting the text after a specific line?
"Jesús Gabriel y Galán" <jgabrielygalan@gmail.com> wrote in post #1056852:
···
On Mon, Apr 16, 2012 at 9:09 PM, fox foxmaster <lists@ruby-forum.com> > wrote:
Hi all,
Does anyone have a solution on how to either see the problems with the
above code or a solution on how to do it with reading line by line and
inserting the text after a specific line?
Something like this should work:
File.open("destination.txt", "w") do |out|
File.foreach("original.txt") do |line|
out.puts line
if line =~ /YOUR_REGEX/
out.puts "THE NEW LINE"
end
end
end