Appending Newline to File Ends with Ruby
I recently took over managing some config files from my dev colleagues. I was extremely annoyed to be reminded that Notepad (Windows’ text editor) does 2 major Unix-incompatible things:
- CRLF line ending (
\r\n
and not\n
) - No newline at the end of file, which is something of a nicety to help process files (allows you to assume each line ends with
\n
).
We can seevim
complaigining about it:
Andgit
too:
Issue 1 is easily solved with dos2unix
, like this:
find -not -path '*/.git/*' -type f | xargs dos2unix
Issue 2 is a little bit more challenging, and I wrote this ruby oneliner for it:
Dir.glob("**/**").select{|f|File.file?(f)}.select{|f|!File.read(f)[/\n$/]}.each{|f|File.open(f,'a'){|h|h<<"\n"}}
Works nicely.