Shereen Andarson
Shereen Andarson

Reputation: 23

How to edit each line of a file in Ruby, without using a temp file

Is there a way to edit each line in a file, without involving 2 files? Say, the original file has,

test01
test02
test03

I want to edit it like

test01,a
test02,a
test03,a

Tried something as show in the code block, but it replaces some of the characters.

Writing it to a temporary file and then replace the original file works, However, I need to edit the file quite often and therefore prefer to do it within the file itself .Any pointers are appreciated.

Thank you!

File.open('mytest.csv', 'r+') do |file|
  file.each_line do |line|        
      file.seek(-line.length, IO::SEEK_CUR)
      file.puts 'a'        
  end
end

Upvotes: 0

Views: 1005

Answers (2)

DigitalRoss
DigitalRoss

Reputation: 146073

f = open 'mytest.csv', 'r+'
r = f.readlines.map { |e| e.strip << ',a' }
f.rewind
f.puts r
f.close # you can leave out this line if it's the last one that runs

Here is a one-liner variation, note that in this case 2 descriptors are left open until the program exits.

open(F='mytest.csv','r+').puts open(F,'r').readlines.map{|e|e.strip<<',a'}

Upvotes: 1

Mark Reed
Mark Reed

Reputation: 95252

Writing to a file doesn't insert; it always overwrites. This makes it awkward to modify text in-place, because you have to rewrite the entire rest of the contents of the file every time you add something new.

If the file is small enough to fit in memory, you can read it in, modify it, and write it back out. Otherwise, you really are better off with the temporary file.

Upvotes: 0

Related Questions