# Add some content to a file

**URL:** <https://www.ruby-forum.com/t/add-some-content-to-a-file/182969>\
**Category:** Ruby\
**Created:** [February 5, 2010, 11:46am UTC](https://www.ruby-forum.com/t/add-some-content-to-a-file/182969 "2010-02-05T11:46:18Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![rubynut](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/8e8cbc/32.png) [@rubynut](https://www.ruby-forum.com/u/rubynut)\
**Post date:** [February 5, 2010, 11:46am UTC](https://www.ruby-forum.com/t/add-some-content-to-a-file/182969/1 "2010-02-05T11:46:18Z")

</div>

Hello,

I want to modify a file, begin from X line (X is line number),  
inserting some content into it.  
I tried scripting it with ruby but couldn’t find a correct way.  
Can you help with it? Thanks.

Jenn.

---

<div class="post-metadata">

**Author:** ![rubynut](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/8e8cbc/32.png) [@rubynut](https://www.ruby-forum.com/u/rubynut)\
**Post date:** [February 5, 2010, 12:35pm UTC](https://www.ruby-forum.com/t/add-some-content-to-a-file/182969/2 "2010-02-05T12:35:28Z")

</div>

On 02/05/2010 11:43 AM, Ruby N. wrote:

> I want to modify a file, begin from X line (X is line number),  
> inserting some content into it.  
> I tried scripting it with ruby but couldn’t find a correct way.  
> Can you help with it? Thanks.

Inserting is hard - because you have to move all the content behind that  
line to the end of the file. It’s easier if you just read the original  
file and write it to another file. Read X - 1 lines from source file  
and write them to temp file. Then write the new content. Then write  
the remainder of the file.

If you want to do the insertion with a single file only you need to  
determine the file offset of line X and then start moving blocks of data  
starting from the end, e.g. read 4k from the end, seek to pos +  
inserted.length, write the 4k. Move back to the second but last 4k,  
read them seek to pos + inserted.length, write them etc. This is more  
complicated to write and also likely more inefficient IO wise.

Kind regards

robert
