Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepend a single line to file with Ruby

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" on its own line
hello
something
else

The following code just replaces the contents of the entire file:

f = File.new('myfile', 'w')
f.write "test string"
like image 354
MrDatabase Avatar asked Dec 24 '11 07:12

MrDatabase


People also ask

How to append data to file in Ruby?

Solution: Appending text to a file with Ruby is similar to other languages: you open the file in "append" mode, write your data, and then close the file. Here's a quick example that demonstrates how to append "Hello, world" to a file named myfile. out in the current directory: open('myfile.

How do you make a new line in Ruby?

"\n" is newline, '\n\ is literally backslash and n.

How do I read a text file in Ruby?

Here is the another example of opening a file in Ruby. fileObject = File. open("tutorials. txt","r"); print(fileObject.


2 Answers

This is a pretty common task:

original_file = './original_file'
new_file = original_file + '.new'

Set up the test:

File.open(original_file, 'w') do |fo|
  %w[something else].each { |w| fo.puts w }
end

This is the actual code:

File.open(new_file, 'w') do |fo|
  fo.puts 'hello'
  File.foreach(original_file) do |li|
    fo.puts li
  end
end

Rename the old file to something safe:

File.rename(original_file, original_file + '.old')
File.rename(new_file, original_file)

Show that it works:

puts `cat #{original_file}`
puts '---'
puts `cat #{original_file}.old`

Which outputs:

hello
something
else
---
something
else

You don't want to try to load the file completely into memory. That'll work until you get a file that is bigger than your RAM allocation, and the machine goes to a crawl, or worse, crashes.

Instead, read it line by line. Reading individual lines is still extremely fast, and is scalable. You'll have to have enough room on your drive to store the original and the temporary file.

like image 51
the Tin Man Avatar answered Sep 30 '22 01:09

the Tin Man


fwiw this seems to work:

#!usr/bin/ruby

f = File.open("myfile", "r+")
lines = f.readlines
f.close

lines = ["something\n"] + lines

output = File.new("myfile", "w")
lines.each { |line| output.write line }
output.close
like image 27
MrDatabase Avatar answered Sep 29 '22 23:09

MrDatabase