Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a string into a textfile

I have a configuration file to which I want to add a string, that looks e.g. like that:

line1
line2
line3
line4

The new string should not be appended but written somewhere into the middle of the file. Therefore I am looking for a specific position (or string) in the file and when it has been found, I insert my new string:

file = File.open(path,"r+")
while (!file.eof?)
  line = file.readline
  if (line.downcase.starts_with?("line1"))
    file.write("Some nice little sentence")
  end
end

The problem is that Ruby overwrites the line in that position with the new text, so the result is the following:

line1
Some nice little sentence
line3
line4

What I want is a "real" insertion:

line1
Some nice little sentence
line2
line3
line4

How can this be achieved?

like image 240
auralbee Avatar asked Jan 26 '10 11:01

auralbee


People also ask

Can strings be written to a file?

Strings can easily be written to and read from a file.

How do I write to a text file?

Steps for writing to text files First, open the text file for writing (or append) using the open() function. Second, write to the text file using the write() or writelines() method. Third, close the file using the close() method.


1 Answers

def replace(filepath, regexp, *args, &block)
  content = File.read(filepath).gsub(regexp, *args, &block)
  File.open(filepath, 'wb') { |file| file.write(content) }
end


replace(my_file, /^line2/mi) { |match| "Some nice little sentence"}

line1
Some nice little sentence
line2
line3
line4

and if you want to append to the existing...

replace(my_file, /^line2/mi) do |match| 
  "#{match} Some nice little sentence"
end

line1
line2 Some nice little sentence
line2
line3
line4
like image 100
ffoeg Avatar answered Sep 28 '22 01:09

ffoeg