跨平台文字檔交換常遇到換行符不一致:Windows 用 CRLF (0x0D 0x0A, \r\n),Linux/Unix 用 LF (0x0A, \n)。此外,copy 合併文字檔會在尾端殘留 EOF 標記 0x1A (Ctrl+Z)。本文整理多種檢測與移除方法,涵蓋 Linux、Windows、編輯器、腳本等場景。
| 方法 | 指令 | 特徵輸出 |
|---|---|---|
file | file dosfile.txt | 顯示 CRLF 或 with CRLF line terminators |
cat -A | cat -A dosfile.txt | 行尾顯示 ^M$ (^M 即 CR) |
od -c | od -c dosfile.txt | head | 顯示 \r\n 雙字元 |
| Notepad++ | 視圖 → 顯示符號 → 顯示換行符 | 行尾顯示 CRLF |
| 工具 | 指令/操作 | 備註 |
|---|---|---|
vim | :set ff=unix → :w | 或 :%s/\r//g 手動替換 |
dos2unix | dos2unix dosfile.txt | 專用工具,支援批次 |
sed | sed 's/\r//g' dosfile.txt > unixfile.txt | 流編輯器,適合管道 |
tr | tr -d '\r' < dosfile.txt > unixfile.txt | 刪除所有 CR |
awk | awk '{sub(/\r$/,"")}1' dosfile.txt > unixfile.txt | 處理每行結尾 CR |
perl | perl -pe 's/\r//g' dosfile.txt > unixfile.txt | 單行腳本 |
unix2dos unixfile.txt (專用工具)sed 's/$/\r/' unixfile.txt > dosfile.txt問題:copy a.txt+b.txt c.txt 產生的 c.txt 尾端會多一個 0x1A (Ctrl+Z),因 copy 預設為文字模式。
解決:指定 二進位模式 /b:
copy /b a.txt+b.txt c.txt
/b 告訴 copy 視為二進位檔案,不加入 EOF 標記,亦不截斷於 0x1A。適用於任何二進位檔合併(圖片、壓縮包、執行檔)。
# CRLF → LF
Get-Content dosfile.txt | Set-Content -Encoding utf8 unixfile.txt
# LF → CRLF
Get-Content unixfile.txt | Set-Content -Encoding utf8 dosfile.txt -NewLine "`r`n"
.gitattributes 設定 * text=auto,自動處理換行符。#!/bin/bash 確保 LF;批次檔無特殊要求但建議 LF。