跨平台文本交換時,換行符不一致是經典坑:Windows 用 CRLF (\r\n, 0x0D0A),Linux/Unix 用 LF (\n, 0x0A),舊 Mac 用 CR (\r, 0x0D)。本文溯源歷史、展示現象、提供多種轉換方案。
Unix 為節省存儲簡化為單一 LF;Windows 保留雙字符;Mac OS 9 及之前用 CR。
| 源格式 | 在 Windows 記事本 | 在 Linux (cat/vim) | 在舊 Mac |
|---|---|---|---|
| LF (Unix) | 整文本變單行,無換行 | 正常 | 行尾顯示 ^J |
| CRLF (Win) | 正常 | 行尾出現 ^M (\r) | 行尾顯示 ^M |
| CR (Old Mac) | 整文本疊在一行 | 行尾顯示 ^M | 正常 |
# Linux → Windows (LF → CRLF)
unix2dos file.txt
# 或
dos2unix -u file.txt # -u 反向轉換
# Windows → Linux (CRLF → LF)
dos2unix file.txt
# 或
unix2dos -u file.txt
# 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
# 刪除所有 \r (CRLF→LF)
cat win.txt | tr -d '\r' > linux.txt
# 輸入 ^M 技巧:Ctrl+V 然後 Ctrl+M
:set fileformat=dos # 存為 CRLF
:set fileformat=unix # 存為 LF
:w # 寫入生效
# 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
find . -type f -name "*.txt" -exec dos2unix {} \;
# 或保留原文件備份
find . -type f -name "*.txt" -exec dos2unix -b {} \;
open(..., newline='') 保持原樣;universal_newlines=True 自動轉換為 \nBufferedReader.readLine() 自動處理三種格式bufio.Scanner 默認按 \n 分割,需自定義 SplitFunc 處理 \r\nfgets 保留換行符,需手動去除 \r# 提交時轉 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 精確控制二進制文件不轉換。