简体   繁体   English

如何使用ruby写入文本文件中的特定行

[英]How to write to a specific line in a text file using ruby

Alright, so I have a ruby file and a text file. 好了,所以我有一个ruby文件和一个文本文件。 The code is like this: 代码是这样的:

fname = "sample.txt"
somefile = File.open(fname, "a")
somefile.puts "Hello file!"
somefile.close

so what i'd like to do is instead of adding it to the end of the file, add it to a specific line. 所以我想做的是代替将其添加到文件末尾,而是将其添加到特定行。 The text file looks like this: 文本文件如下所示:

names
kyle
andrew
joshua
devon

so what I'd like to be able to do it to insert text between "kyle" and "andrew", with each on a seperate line. 因此,我希望能够在“凯尔”和“安德鲁”之间插入文本,并且每个文本都在单独的一行上。 Please help 请帮忙

Random access is for read-only purpose, if you want to write a random line: 如果要写入随机行,则随机访问仅用于只读目的:

  • read the file 读取文件
  • find the line you want to append text 找到要追加文本的行
  • append and write a new file 追加并写入新文件
require 'stringio'
tmp = StringIO.open
origin.each do |line|
  tmp<<line
  if line == 'kyle'
    tmp << 'new line !'
  end
end
tmp.seek 0
File.open(fname, "wb").write tmp.read

the file then looks like: 该文件如下所示:

names
kyle
new line !
andrew
joshua
devon

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM