sorrell
sorrell

Reputation: 1871

How to determine line ending types in Ruby

I am using CSVLint to run some validation on flat files. The sources for the files can have varied line endings, some are \n, some \r\n. The Validator constructor takes a dialect parameter where I need to specify the line ending type.

Is there a good/quick/easy way to sample the first line of the flat file to determine the line ending type in Ruby?

Update

The answer below is the correct answer to my question. If you need auto line endings in CSVLint, however, try this in the dialect:

"lineTerminator" => :auto

Also, @sawa's answer below pertains to my original question (and typo) of looking for \r and \r\n.

Upvotes: 2

Views: 672

Answers (2)

Jordan Running
Jordan Running

Reputation: 106077

To detect \n and \r\n line endings, simply match the first line against the regular expression /\r?\n$/:

def determine_line_ending(filename)
  File.open(filename, 'r') do |file|
    return file.readline[/\r?\n$/]
  end
end

determine_line_ending('./windows_file.csv')
# => "\r\n"

determine_line_ending('./unix_file.csv')
# => "\n"

This doesn't handle weird edge cases like the Mac OS 9 (discontinued in 2001) \r line ending, but covers everything else. If you want some background on historical line endings, the Wikipedia article is pretty interesting.

Upvotes: 2

sawa
sawa

Reputation: 168199

Edit The following is an answer to the original question, not the question after it has changed.

When you have the first line line,

line[/[\r\n]+/]

will give you what line ending you have.

Upvotes: 1

Related Questions