Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert text into existing file

I have a txt file.how can I place some text among that and don't overwrite it? because when I use for example f.puts "aaaaaaaaaaaaaaa" Ruby overwrites my txt file . thanks

like image 773
amir amir Avatar asked Aug 16 '11 22:08

amir amir


People also ask

How do I insert text into an existing document?

Go to Insert > Text Box, and then select Draw Text Box. Click or tap in the document, and drag to draw the text box the size that you want. To add text to a text box, select inside the text box, and then type or paste text.

How do I add text to an existing file in Java?

In Java, we can append a string in an existing file using FileWriter which has an option to open a file in append mode. Java FileWriter class is used to write character-oriented data to a file. It is a character-oriented class that is used for file handling in Java.

How do I insert text from a downloaded file?

Position the cursor where you want to insert the document. Go to the Insert tab. In the Text group, select the Object drop-down arrow. Select Text from File.

How do you add text to a file in Python?

To write to a text file in Python, you follow these steps: 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.

How do I add text to a file in Linux?

The tee command copies the text from standard input and writes it to the standard output file. The tee provides -a option to append the text to the file. This is how we append the text into a file in Linux.


2 Answers

You need to open it in append mode

File.open("file.txt", "a+"){|f| f << "aaaaaaaaaaaaaaaaaaa" }

Check out your previous question

File opening mode in Ruby

like image 133
fl00r Avatar answered Nov 04 '22 05:11

fl00r


If you're asking how to insert text into the middle of an existing file, as below, you can't:

Original file first half, Original File second half

becomes:

Original file first half, Inserted text, Original File second half

You need to make a new file, copy the first half of the original into it, then write the new text, then copy the rest of the original file.

like image 35
RichieHindle Avatar answered Nov 04 '22 05:11

RichieHindle