# How to check for where a text file begins?

**URL:** <https://www.ruby-forum.com/t/how-to-check-for-where-a-text-file-begins/108389>\
**Category:** Ruby\
**Created:** [July 3, 2007, 1:08am UTC](https://www.ruby-forum.com/t/how-to-check-for-where-a-text-file-begins/108389 "2007-07-03T01:08:39Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![desertfox](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/8491ac/32.png) [@desertfox](https://www.ruby-forum.com/u/desertfox)\
**Post date:** [July 3, 2007, 1:08am UTC](https://www.ruby-forum.com/t/how-to-check-for-where-a-text-file-begins/108389/1 "2007-07-03T01:08:39Z")

</div>

Hello,

Im working with some imported text files and I need check where the  
first 2 lines of text occur. The files can have white space in the  
beginning, so I cant just do a split("\n") and take the first two  
elements of the array. Im a bit confused about this stuff. Here is  
what I’ve been trying to do with regular expressions, but no results  
yet:

def find\_first\_two\_lines(file)  
/\S\n\S/.match(file)  
end

If anyone has any ideas, please do share!

Thanks in advance!

---

<div class="post-metadata">

**Author:** ![desertfox](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/8491ac/32.png) [@desertfox](https://www.ruby-forum.com/u/desertfox)\
**Post date:** [July 3, 2007, 1:20am UTC](https://www.ruby-forum.com/t/how-to-check-for-where-a-text-file-begins/108389/2 "2007-07-03T01:20:33Z")

</div>

def find\_first\_two\_lines(text)  
text.strip.split(“\n”).slice(0,2)  
end

Returns an array of the first two non whitespace lines delimited by \n

(\n is also included in whitespace per strip… handly)

Regards

Mikel L.

> **[The Construction Blog - Tips on Choosing Local Construction Companies](http://www.blognow.com.au)**
>
> Tips on Choosing Local Construction Companies

---

<div class="post-metadata">

**Author:** ![desertfox](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/8491ac/32.png) [@desertfox](https://www.ruby-forum.com/u/desertfox)\
**Post date:** [July 3, 2007, 4:34pm UTC](https://www.ruby-forum.com/t/how-to-check-for-where-a-text-file-begins/108389/3 "2007-07-03T16:34:41Z")

</div>

2007/7/3, Al Cholic [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

> /\S\n\S/.match(file)  
> end
> 
> If anyone has any ideas, please do share!

What exactly do you want to do with them? If you have your file  
contents in a single string you can do s.sub(/^\s+/, ‘’) in order to  
get rid of all leading whitespace. You can as well do the checking  
during reading, probably like this:

contents = nil  
io.each do |line|  
contents = “” if contents.nil? && /^\s\*$/ =~ line  
contents \<\< line if contents  
end

Kind regards

robert
