Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux/Windows 換行符差異(LF vs CRLF)與跨平台檔案處理最佳實踐

編輯:Linux 教學

歷史根源

  • Windows (CRLF, \r\n, 0x0D 0x0A):源自電傳打字機 —— \r (Carriage Return) 歸位打印頭,\n (Line Feed) 捲紙換行,兩動作合一。
  • Unix/Linux (LF, \n, 0x0A):簡化為單一控制字符,僅 \n 同時完成歸位與換行。
  • Mac OS 9 及之前 (CR, \r, 0x0D):僅歸位,現已罕見。

實際踩坑場景

// Java PrintWriter 在 Linux 下 println() 寫入 \n
// Windows 記事本開啟 → 全文黏在一行(不識別單獨 LF)
// Notepad++ / VS Code / 現代編輯器均可正確顯示

轉換工具與指令

程式碼層面最佳實踐

  • Git 設定:git config --global core.autocrlf input(提交轉 LF,簽出不轉),Windows 端用 true。
  • .gitattributes 強制規範:* text=auto eol=lf。
  • 程式語言:Java System.lineSeparator()、Python os.linesep、Node require('os').EOL、Go runtime.GOOS 判斷,避免硬編碼 \n 或 \r\n。
  • 網路協議:HTTP/Email 標頭規定 \r\n,Body 視 Content-Type;自行實作協議時嚴格遵循 RFC。

快速檢測檔案換行符

file -b file.txt          # 輸出含 "CRLF" 或 "LF"
cat -A file.txt           # ^M$ 表示 CRLF,$ 表示 LF
od -c file.txt | head     # 直接看 16 進位: \r \n vs \n
Copyright © Windows教程網 All Rights Reserved
方向工具/指令
LF → CRLFunix2dos file.txt、sed 's/$/\r/'、awk '{print $0 "\r"}'
CRLF → LFdos2unix file.txt、sed 's/\r$//'、tr -d '\r'
編輯器設定VS Code 右下角 CRLF/LF 切換、Notepad++「格式」選單、Vim :set fileformat=dos/unix