[翻译]  How to insert a string into a textfile

[CHINESE]  如何将字符串插入文本文件


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:

问题是Ruby用新文本覆盖该位置的行,因此结果如下:

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?

怎么能实现这一目标?

4 个解决方案

#1


11  

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.

这就是Rails在幕后做的方式。

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

或者你可以逐行复制它,然后用mv覆盖原文,如下所示:

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\n"
  end
end
f.close
tempfile.close

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

#2


7  

def replace(filepath, regexp, *args, &block)
  content = File.read(filepath).gsub(regexp, *args, &block)
  File.open(filepath, 'wb') { |file| file.write(content) }
end


replace(my_file, /^line2/mi) { |match| "Some nice little sentence"}

line1
Some nice little sentence
line2
line3
line4

and if you want to append to the existing...

如果你想附加到现有...

replace(my_file, /^line2/mi) do |match| 
  "#{match} Some nice little sentence"
end

line1
line2 Some nice little sentence
line2
line3
line4

#3


4  

A couple other options:

其他两个选择:

file = File.read(path).sub(/line2\n/, 'Some nice little sentence\n\1')
File.write(path, file)

file = File.readlines(path)
index = file.index("line2")
file.insert(index, "Some nice little sentence")
File.write(path, file)

#4


0  

The easiest way is to read the whole file in memory, then write the first part back to the file, write your inserted line to the file, and write the remaining part back to the file. This should be relatively simple to do when you read the file as an array of lines, but you might run into problems if your file is very large since you have to read the entire file into memory with this approach.

最简单的方法是读取内存中的整个文件,然后将第一部分写回文件,将插入的行写入文件,然后将剩余部分写回文件。当您将文件作为行数组读取时,这应该相对简单,但如果您的文件非常大,则可能会遇到问题,因为您必须使用此方法将整个文件读入内存。

Alternatively you could find the spot that you want to insert the line, read the lines after that point into memory, seek back to that point in the file, write your new line to the file, and finally write the remaining lines to the file. Again you'll run into problems if the remainder of the file is very large since you have to read it all into memory.

或者,您可以找到要插入线的点,将该点后的行读入内存,在文件中找回该点,将新行写入文件,最后将剩余的行写入文件。如果文件的其余部分非常大,您将再次遇到问题,因为您必须将其全部读入内存。

A third approach is to write the first part into a new file, write the inserted line into a new file, write the remainder of the original file into the new file, and finally replace the old file with the new file on the file system. This approach allows you to deal with one line at a time so you can handle files that do not fit into memory.

第三种方法是将第一部分写入新文件,将插入的行写入新文件,将原始文件的剩余部分写入新文件,最后用文件系统上的新文件替换旧文件。此方法允许您一次处理一行,以便您可以处理不适合内存的文件。

The reason why file writing works like this is because the file is like a fixed size array of bytes: when you write a byte to the file you will overwrite an existing byte (I'm ignoring the case where you append to a file here). So the only way to insert anything to a file is to first move the old content to a new location by reading it from the old location and writing it to the new location. After that you can 'insert' data into the now vacant area.

文件写入这样工作的原因是因为文件类似于固定大小的字节数组:当您向文件写入一个字节时,您将覆盖现有字节(我忽略了您在此处附加到文件的情况) 。因此,向文件中插入任何内容的唯一方法是首先将旧内容从旧位置读取并将其写入新位置,然后将其移动到新位置。之后,您可以将数据“插入”现在空置的区域。


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号