Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

ruby on rails - How to insert a string into a textfile

I have a configuration file to which I want to add a string, that looks e.g. like that:

line1
line2
line3
line4

The new string should not be appended but written somewhere into the middle of the file. Therefore I am looking for a specific position (or string) in the file and when it has been found, I insert my new string:

file = File.open(path,"r+")
while (!file.eof?)
  line = file.readline
  if (line.downcase.starts_with?("line1"))
    file.write("Some nice little sentence")
  end
end

The problem is that Ruby overwrites the line in that position with the new text, so the result is the following:

line1
Some nice little sentence
line3
line4

What I want is a "real" insertion:

line1
Some nice little sentence
line2
line3
line4

How can this be achieved?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If it's a small file I think the easiest way would be to:

  • Read the complete file.
  • Insert the line.
  • Write the new file.

That is the way Rails does it behind the scenes.

Or you can copy it line by line and then overwrite the original with mv like this:

require 'fileutils'

tempfile=File.open("file.tmp", 'w')
f=File.new("file.txt")
f.each do |line|
  tempfile<<line
  if line.downcase=~/^line2/
    tempfile << "Some nice little sentence
"
  end
end
f.close
tempfile.close

FileUtils.mv("file.tmp", "file.txt")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...