Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve line endings in Ruby on Windows?

Tags:

ruby

I am running Ruby 1.9.3 on Windows. When I run the following snippet of code

text = File.read(path)
File.write(path, text)

I get the exact same file when the file has CR+LF line endings. When I run this on a file with LF line endings, it changes to CR+LF line endings.

How can I read from and write to a file using Ruby on Windows such that line endings are preserved, whether CR+LF or LF?

like image 225
cm007 Avatar asked Dec 05 '14 19:12

cm007


1 Answers

Ruby, along with Perl and probably Python, are aware of the OS the code is running on, and will automatically set what the line-endings should be.

If you read, then write, a text file, those settings will kick in, and you'll see the file change like you are.

If you need to have the file be unchanged, add a b flag to an open statement, like:

File.open('path', 'wb') do |fo|
  fo.write(text)
end

For more information, see "IO Open Mode".

like image 144
the Tin Man Avatar answered Sep 19 '22 04:09

the Tin Man