Neil Hoff
Neil Hoff

Reputation: 2075

Ruby: Append text to the 2nd line of a file

The Ruby script i am writing is going to be run every morning and will pull information about backup files and write them to a csv file. This file has column names on the first line.

I have gotten it to work by appending to the end of the file:

open("#{curDir}/Backup_Times.csv", 'a') do |f|

        ...
end

I would like to see the newest data first without having to sort in Excel.

In Ruby, is there a way to write this data starting at the 2nd line of the file?

Upvotes: 1

Views: 2269

Answers (1)

dbenhur
dbenhur

Reputation: 20408

You write a new file, applying your change at the desired line, then rename result back to the original file name. The following method will copy the file and yield the output file object to a block at the correct line, so that block can output your new lines.

def insert_lines_following_line file, line_no
  tmp_fn = "#{file}.tmp"
  File.open( tmp_fn, 'w' ) do |outf|
    line_ct = 0
    IO.foreach(file) do |line|
      outf.print line
      yield(outf) if line_no == (line_ct += 1)
    end
  end
  File.rename tmp_fn, file
end

insert_lines_following_line( "#{curDir}/Backup_Times.csv", 1 ) do |outf|
  # output new csv lines in this block
  outf.puts ['foo','bar','baz',1,2,3].join(",") # or however you build your csv line
end

Upvotes: 2

Related Questions