dos2unix:修复脚本和文本文件的 CRLF 换行符
在 Linux 上把 Windows 换行符转换为 Unix 格式(unix2dos 反向转换)。
执行 dos2unix 文件 即可删除 CR 字符、把 CRLF 转为 LF;反向转换用 unix2dos。
01命令
命令
$ dos2unix script.sh && unix2dos notes.txt02作用说明
在 Windows 上编辑过的文件带 \r\n 换行,Linux 工具会把它显示成多余的 ^M 字符,更糟的是会破坏 shebang,让脚本报错“/bin/bash^M: bad interpreter”。dos2unix 直接原地删除 CR 字节;当 Windows 工具要求 CRLF 时,unix2dos 可以再加回去。没装这个包时可用 tr -d '\r' 或 sed -i 's/\r$//' 等价替代,但 dos2unix 对 BOM 和老式 Mac 换行的处理更完备。
03风险
!注意: dos2unix 会原地改写文件;用 -n 输入 输出 可转换到新文件,切勿对二进制文件使用。
04撤销
撤销
$ unix2dos FILE (converts back to CRLF)05来源
- dos2unix(1) — Ubuntu manpage依据: dos2unix converts DOS/Mac line breaks to Unix; unix2dos does the reverse; -n writes to a new file, -c sets conversion mode
- dos2unix(1) — Arch Linux manual依据: dos2unix converts line breaks from DOS/Mac to Unix; unix2dos does the reverse; -n writes to a new file, -c sets conversion mode
最后验证: 2026-09-17 · 分类: 文件与文件夹