萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux/Windows 換行符差異(CRLF vs LF)根因與轉換工具全解析

跨平台文本交換時,換行符不一致是經典坑:Windows 用 CRLF (\r\n, 0x0D0A),Linux/Unix 用 LF (\n, 0x0A),舊 Mac 用 CR (\r, 0x0D)。本文溯源歷史、展示現象、提供多種轉換方案。

歷史溯源:電傳打字機的遺產

  • CR (Carriage Return, \r):打印頭歸位左邊界
  • LF (Line Feed, \n):紙卷向上捲一行
  • 機械限制:換行需 0.2 秒,為避免丟字符,約定雙字符結尾

Unix 為節省存儲簡化為單一 LF;Windows 保留雙字符;Mac OS 9 及之前用 CR。

跨平台顯示現象

源格式在 Windows 記事本在 Linux (cat/vim)在舊 Mac
LF (Unix)整文本變單行,無換行正常行尾顯示 ^J
CRLF (Win)正常行尾出現 ^M (\r)行尾顯示 ^M
CR (Old Mac)整文本疊在一行行尾顯示 ^M正常

轉換工具與命令

1. 專用雙向轉換工具(推薦)

# Linux → Windows (LF → CRLF)
unix2dos file.txt
# 或
dos2unix -u file.txt   # -u 反向轉換

# Windows → Linux (CRLF → LF)
dos2unix file.txt
# 或
unix2dos -u file.txt

2. sed 就地替換

# CRLF → LF
sed -i 's/\r$//' file.txt
# 或
sed -i 's/\r\n/\n/g' file.txt

# LF → CRLF
sed -i 's/$/\r/' file.txt

3. tr 刪除/替換

# 刪除所有 \r (CRLF→LF)
cat win.txt | tr -d '\r' > linux.txt
# 輸入 ^M 技巧:Ctrl+V 然後 Ctrl+M

4. Vim 內部轉換

:set fileformat=dos   # 存為 CRLF
:set fileformat=unix  # 存為 LF
:w                    # 寫入生效

5. Python 一行命令

# CRLF → LF
python -c "import sys; sys.stdout.write(sys.stdin.read().replace('\r\n','\n'))" < win.txt > linux.txt

# LF → CRLF
python -c "import sys; sys.stdout.write(sys.stdin.read().replace('\n','\r\n'))" < linux.txt > win.txt

6. 批量轉換目錄下所有文本文件

find . -type f -name "*.txt" -exec dos2unix {} \;
# 或保留原文件備份
find . -type f -name "*.txt" -exec dos2unix -b {} \;

編程語言處理建議

  • Python:open(..., newline='') 保持原樣;universal_newlines=True 自動轉換為 \n
  • Java:BufferedReader.readLine() 自動處理三種格式
  • Go:bufio.Scanner 默認按 \n 分割,需自定義 SplitFunc 處理 \r\n
  • C/C++:fgets 保留換行符,需手動去除 \r

Git 管理策略

# 提交時轉 LF,檢出時轉 CRLF (Windows)
git config --global core.autocrlf true

# 提交時轉 LF,檢出不轉換 (Linux/Mac)
git config --global core.autocrlf input

# 拒絕混合換行符提交
git config --global core.safecrlf warn

團隊協作建議:倉庫統一存 LF,Windows 端開啟 core.autocrlf=true,.gitattributes 精確控制二進制文件不轉換。

copyright © 萬盛學電腦網 all rights reserved