unix2dos 和 dos2unix 通常是同一个软件包中的两个命令,用于在Unix/Linux和DOS/Windows文本格式之间相互转换。
unix2dos 是 dos2unix 的反向工具,用于将Unix/Linux格式的文本文件转换为DOS/Windows格式。主要处理换行符的转换:
这在需要将Linux服务器上的文件传输到Windows系统使用时特别有用。
大多数Linux发行版中,unix2dos 和 dos2unix 包含在同一个软件包中:
# Ubuntu/Debian
sudo apt-get install dos2unix
# CentOS/RHEL/Fedora
sudo yum install dos2unix
# 或
sudo dnf install dos2unix
# Arch Linux
sudo pacman -S dos2unix
# 安装后验证
unix2dos --version
dos2unix --version
# 基本格式
unix2dos [选项] 文件1 [文件2 ...]
# 与dos2unix对比
dos2unix [选项] 文件1 [文件2 ...] # Unix转DOS
unix2dos [选项] 文件1 [文件2 ...] # DOS转Unix
| 选项 | 说明 | 示例 |
|---|---|---|
-k, --keepdate |
保持文件时间戳不变 | unix2dos -k file.txt |
-n, --newfile |
新文件模式(保留原文件) | unix2dos -n input.txt output.txt |
-o, --oldfile |
覆盖原文件(默认) | unix2dos -o script.sh |
-q, --quiet |
静默模式,不显示警告 | unix2dos -q file.txt |
-c, --convmode |
转换模式 (ascii, 7bit, iso, mac等) | unix2dos -c ascii file.txt |
-f, --force |
强制转换二进制文件 | unix2dos -f data.bin |
-V, --version |
显示版本信息 | unix2dos -V |
-h, --help |
显示帮助信息 | unix2dos -h |
# 转换单个文件(覆盖原文件)
unix2dos linux_script.sh
# 转换并保留时间戳
unix2dos -k config.conf
# 转换并创建新文件(原文件保留)
unix2dos -n source.py windows_version.py
# 静默模式转换
unix2dos -q logfile.txt
# 转换当前目录所有.sh文件
unix2dos *.sh
# 转换多个指定文件
unix2dos file1.txt file2.md file3.py
# 递归转换目录下所有文本文件
find /home/user/docs -name "*.txt" -exec unix2dos {} \;
# 结合xargs批量转换
find /var/www/html -name "*.php" -print0 | xargs -0 unix2dos
# 场景1:将Linux服务器配置文件提供给Windows用户
unix2dos /etc/nginx/nginx.conf
# 现在可以在Windows记事本中正常查看
# 场景2:将Shell脚本转换为Windows批处理兼容格式
unix2dos backup_script.sh
# 虽然不能直接执行,但可以在Windows编辑器中正确显示
# 场景3:准备Windows部署文件
# 将Linux下编写的README文件转换为Windows格式
unix2dos README.md INSTALL.txt CHANGELOG.txt
# 场景4:处理源代码文件
find /project/src -name "*.java" -o -name "*.xml" | xargs unix2dos
# 检查文件当前格式
file document.txt
# 查看换行符(转换前)
od -c document.txt | grep -n "\\n\\|\\r"
# 查看换行符(转换后)
unix2dos document.txt
od -c document.txt | head -5
# 使用hexdump查看二进制格式
hexdump -C document.txt | head -10
| 命令 | 功能 | 转换方向 | 典型用途 |
|---|---|---|---|
unix2dos |
Unix转DOS格式 | LF → CR+LF | Linux文件在Windows使用 |
dos2unix |
DOS转Unix格式 | CR+LF → LF | Windows文件在Linux使用 |
# 1. 使用sed命令替代unix2dos
sed -i 's/$/\r/' unixfile.txt # 简单转换
sed -i -e 's/$/\r/' -e 's/\r\r/\r/' file.txt # 避免重复\r
# 2. 使用awk命令
awk 'sub("$", "\r")' unix.txt > dos.txt
# 3. 使用Perl一行命令
perl -pe 's/\n/\r\n/' < input.txt > output.txt
# 4. 使用Python脚本
python3 -c "import sys; [sys.stdout.write(line.rstrip('\n') + '\r\n') for line in sys.stdin]" < input.txt
# 5. 使用Vim编辑器
# 在vim中执行
# :set ff=dos
# :wq
需要安装dos2unix软件包:sudo apt install dos2unix 或 sudo yum install dos2unix
正常现象。每行多了一个\r字符,文件大小会增加(行数×1字节)。
使用反向命令:dos2unix 文件名