I\'d like to add a single line to the top a of file with Ruby like this:
# initial file contents
something
else
# file contents after prepending \"hello\" o
Pure, but works. Minimize file-related operations.
`#!/bin/ruby
inv_file = File.open("./1.txt","r+") { |f|
#Read file string by-string
until f.eof?
#Searching for some
if f.readline[/condition here/]
#remember position
offset = f.pos
#Find it? - stop reading
break
end
end
#Remember what contains rest of file
tail = f.readlines
#Again to offset
f.pos = offset
#insert what necessary
f.puts "INSERTED"
#reconstruct tail
f.write tail.join
}`
I have came up with something like this, it is a little bit more descriptive and less cryptic than other solutions I've seen:
def file_prepend(file, str)
new_contents = ""
File.open(file, 'r') do |fd|
contents = fd.read
new_contents = str << contents
end
# Overwrite file but now with prepended string on it
File.open(file, 'w') do |fd|
fd.write(new_contents)
end
end
And you can use it like this:
file_prepend("target_file.txt", "hello world!\n")