简体   繁体   中英

How to write to a specific line in a text file using ruby

Alright, so I have a ruby file and a text file. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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