Line ending drama

1 minute read

The Characters

End of line characters are both control characters, so they should be invisible and only keep track. Carriage Return (CR) is represented by ASCII number 13, and get it’s name from the movement of typewriter to the left of a sheet of paper. The Line Feed (LF) is represented by ASCII number 10, and come from the action of a typewriter rolling a piece of paper up by one line. The combination of these two functions is what does ENTER/RETURN key and puts CRLF character at end of line.

The problems

The problems with file ending comes from the fact that Windows, Mac and *Nix terminate text lines differently:

  • *Nix uses the LF character
  • Macs use the CR character
  • Windows uses both in order CRLF

And this come in your way when you transfer files between OS.

How to fix

In *NIX system you can use tr to translate from one to another:

Windows -> NIX:

    tr -d '\r' <windowsfile> nixfile // delete the CR

Mac -> NIX:

    tr '\r' '\n' <macfile> nixfile // translate CR into LF

NIX -> Mac:

    tr '\n' '\r' <nixfile> macfile //translate LF into CR

In VIM/Neovim you can use %s substitute on all lines in current file.

Windows -> NIX:

Remove ^M that shows at end of all lines

    :%s/<Ctrl-V><Ctrl-M>/\r/g

Or try change file format around the three( unix, mac and dos). In theory when file is saved it should rewrites the file in the correct format.

    :set fileformat = unix
    :w

Leave a Comment