LF and CRLF line endings: why the whole file looks changed

Topic illustration for the article: LF and CRLF line endings: why the whole file looks changed
Practical illustration for this guide

A file can look unchanged while version control reports every line replaced. Often LF became CRLF or the reverse. This is not an extra space: the line ending is part of the text’s structure.

Load a mixed-line-ending sample

Three common representations

LF is U+000A, CR is U+000D and CRLF is the pair U+000D U+000A. Unix-like systems usually use LF, Windows text commonly uses CRLF and legacy formats may contain lone CR. Treat CRLF as one ending.

Mixed endings hide in editors

Most editors draw the same break for all variants. Inspect hex or reveal end-of-line marks. Count CRLF, lone LF and lone CR, excluding characters already consumed by a pair.

Why a diff marks every line

An editor, Git setting, archive tool or generator may convert endings on save. Line content remains the same but bytes change everywhere. Separate that mechanical conversion from semantic edits before review.

Document the repository rule

.gitattributes and editor settings can establish an expected format. Do not rely on one developer’s auto-conversion. Scripts must fit their runtime, while network protocols may impose a different requirement.

Never apply text conversion to binary data

An image, archive or document container can contain 0D 0A as payload. Replacing those bytes corrupts it. Even for text, establish the encoding first; byte-wise splitting of UTF-16 is equally unsafe.

Verify after conversion

Compare logical line count and line content without terminators, then run tests and linters. Record the final byte convention. If a consumer requires CRLF, it is not “dirty” and should not be changed merely to reach a zero counter.

Counting without overlap

The expression treats CRLF as a pair and reports lone CR or LF separately. That prevents the same CRLF ending from being interpreted as both a CR case and an LF case.

const text = "one\r\ntwo\nthree\rfour";
const endings = text.match(/\r\n|\r(?!\n)|(?<!\r)\n/g) ?? [];
console.log(endings.map(e => e === "\r\n" ? "CRLF" : e === "\n" ? "LF" : "CR"));

Safe normalization

  1. Confirm text format and encoding.
  2. Count all three ending types.
  3. Check repository or protocol requirements.
  4. Convert one copy once.
  5. Review the diff and run tests.

Open the cleaner

Sources and specifications

Related guides

Author: Mykola. LF and CRLF are both correct in their contexts; consistency and compatibility are the actual goals.