# Insert into textfile

**URL:** <https://www.ruby-forum.com/t/insert-into-textfile/148526>\
**Category:** Ruby\
**Created:** [September 14, 2008, 9:21am UTC](https://www.ruby-forum.com/t/insert-into-textfile/148526 "2008-09-14T09:21:11Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![rgreen](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/f04885/32.png) [@rgreen](https://www.ruby-forum.com/u/rgreen)\
**Post date:** [September 14, 2008, 9:21am UTC](https://www.ruby-forum.com/t/insert-into-textfile/148526/1 "2008-09-14T09:21:11Z")

</div>

I have a text file that I want to insert a new line into between the  
first and second line. Is there a way to do this?

---

<div class="post-metadata">

**Author:** ![rgreen](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/f04885/32.png) [@rgreen](https://www.ruby-forum.com/u/rgreen)\
**Post date:** [September 14, 2008, 2:44pm UTC](https://www.ruby-forum.com/t/insert-into-textfile/148526/2 "2008-09-14T14:44:26Z")

</div>

content = File.read(‘test.txt’)  
content.sub!("\n","\n\n")  
File.open(‘test.txt’,‘w’).write(content)

sub does replace the first occurence of a new line in the file

thomas

---

<div class="post-metadata">

**Author:** ![rgreen](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/f04885/32.png) [@rgreen](https://www.ruby-forum.com/u/rgreen)\
**Post date:** [September 14, 2008, 11:15pm UTC](https://www.ruby-forum.com/t/insert-into-textfile/148526/3 "2008-09-14T23:15:43Z")

</div>

Actually, that was close.  
This is what I was kind of looking for.

content = File.read(‘exam.txt’)  
content.sub!("\n","\nNew Content\n")  
File.open(‘exam.txt’,‘r+’).write(content)

But this doesn’t work if the first line doesn’t end in a new line  
character.
