本文目录导读:

方案1:Python脚本(推荐,跨平台)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
批量替换文本文件换行符脚本
支持 Windows(CRLF) -> Unix(LF) 或 Unix(LF) -> Windows(CRLF)
"""
import os
import sys
import argparse
from pathlib import Path
def convert_line_endings(file_path, target_format='lf'):
"""
转换文件的换行符格式
Args:
file_path: 文件路径
target_format: 'lf' (Unix) 或 'crlf' (Windows)
"""
try:
# 读取文件内容
with open(file_path, 'rb') as f:
content = f.read()
# 根据目标格式进行转换
if target_format == 'lf':
# 将所有换行符转换为 LF
new_content = content.replace(b'\r\n', b'\n').replace(b'\r', b'\n')
elif target_format == 'crlf':
# 将所有换行符转换为 CRLF
new_content = content.replace(b'\r\n', b'\n').replace(b'\r', b'\n')
new_content = new_content.replace(b'\n', b'\r\n')
else:
print(f"不支持的格式: {target_format}")
return False
# 如果内容有变化,写回文件
if content != new_content:
with open(file_path, 'wb') as f:
f.write(new_content)
return True
else:
return False
except Exception as e:
print(f"处理文件 {file_path} 时出错: {e}")
return False
def process_directory(directory_path, target_format='lf', extensions=None):
"""
递归处理目录中的所有文本文件
Args:
directory_path: 目录路径
target_format: 目标换行符格式
extensions: 要处理的文件扩展名列表,如 ['.txt', '.py', '.html']
"""
directory = Path(directory_path)
if not directory.exists():
print(f"目录不存在: {directory_path}")
return
count = 0
for file_path in directory.rglob('*'):
if file_path.is_file():
# 如果指定了扩展名,只处理匹配的文件
if extensions and file_path.suffix.lower() not in extensions:
continue
if convert_line_endings(file_path, target_format):
print(f"已转换: {file_path}")
count += 1
print(f"\n总共转换了 {count} 个文件")
def main():
parser = argparse.ArgumentParser(description='批量替换文本文件换行符')
parser.add_argument('path', help='文件或目录路径')
parser.add_argument('-f', '--format', choices=['lf', 'crlf'],
default='lf', help='目标换行符格式 (lf=Unix, crlf=Windows)')
parser.add_argument('-e', '--extensions', nargs='+',
help='要处理的文件扩展名,如 .txt .py .html')
parser.add_argument('-r', '--recursive', action='store_true',
help='递归处理子目录')
args = parser.parse_args()
path = Path(args.path)
if path.is_file():
# 处理单个文件
if convert_line_endings(path, args.format):
print(f"已转换: {path}")
else:
print(f"文件无需转换: {path}")
elif path.is_dir():
# 处理目录
process_directory(path, args.format, args.extensions)
else:
print(f"路径不存在: {path}")
if __name__ == "__main__":
main()
方案2:Windows 批处理脚本
@echo off
chcp 65001 >nul批量替换换行符脚本
echo ========================================
echo 批量替换文本文件换行符脚本
echo ========================================
echo.
set /p work_dir=请输入要处理的目录路径:
set /p file_ext=请输入文件扩展名(如 *.txt,不指定则处理所有文件):
if "%work_dir%"=="" set work_dir=%cd%
echo.
echo 选择转换方向:
echo 1. CRLF (Windows) -^> LF (Unix/Linux)
echo 2. LF (Unix/Linux) -^> CRLF (Windows)
echo.
set /p choice=请输入选择 (1 或 2):
if "%choice%"=="1" (
echo 正在将 CRLF 转换为 LF...
set "conversion=crlf2lf"
) else (
echo 正在将 LF 转换为 CRLF...
set "conversion=lf2crlf"
)
echo.
echo 处理目录: %work_dir%
echo 文件类型: %file_ext%
echo.
set count=0
for /r "%work_dir%" %%f in (%file_ext%) do (
if exist "%%f" (
set /a count+=1
echo 处理文件: %%f
if "%conversion%"=="crlf2lf" (
:: 使用 VBScript 进行换行符替换
echo Set fso = CreateObject("Scripting.FileSystemObject") > "%temp%\convert.vbs"
echo Set file = fso.OpenTextFile("%%f", 1) >> "%temp%\convert.vbs"
echo content = file.ReadAll >> "%temp%\convert.vbs"
echo file.Close >> "%temp%\convert.vbs"
echo content = Replace(content, vbCrLf, vbLf) >> "%temp%\convert.vbs"
echo Set outfile = fso.OpenTextFile("%%f", 2) >> "%temp%\convert.vbs"
echo outfile.Write content >> "%temp%\convert.vbs"
echo outfile.Close >> "%temp%\convert.vbs"
cscript //nologo "%temp%\convert.vbs"
) else (
:: 使用 VBScript 进行换行符替换
echo Set fso = CreateObject("Scripting.FileSystemObject") > "%temp%\convert.vbs"
echo Set file = fso.OpenTextFile("%%f", 1) >> "%temp%\convert.vbs"
echo content = file.ReadAll >> "%temp%\convert.vbs"
echo file.Close >> "%temp%\convert.vbs"
echo content = Replace(content, vbLf, vbCrLf) >> "%temp%\convert.vbs"
echo Set outfile = fso.OpenTextFile("%%f", 2) >> "%temp%\convert.vbs"
echo outfile.Write content >> "%temp%\convert.vbs"
echo outfile.Close >> "%temp%\convert.vbs"
cscript //nologo "%temp%\convert.vbs"
)
del "%temp%\convert.vbs" 2>nul
)
)
echo.
echo ========================================
echo 处理完成!共处理 %count% 个文件
echo ========================================
echo.
pause
方案3:Linux/Mac Shell 脚本
#!/bin/bash
# 批量替换换行符脚本 - Unix/Linux/Mac
# 使用方法: ./convert_line_endings.sh [目录] [选项]
# 默认设置
TARGET_DIR="${1:-.}"
CONVERT_TO="${2:-lf}" # lf 或 crlf
convert_file() {
local file="$1"
local target="$2"
if [ ! -f "$file" ]; then
return 1
fi
# 检查是否为文本文件(跳过二进制文件)
if file "$file" | grep -q "binary"; then
echo "跳过二进制文件: $file"
return 1
fi
# 转换换行符
case "$target" in
lf)
# CRLF -> LF 或 CR -> LF
sed -i 's/\r$//' "$file"
;;
crlf)
# LF -> CRLF
sed -i 's/$/\r/' "$file"
;;
*)
echo "不支持的格式: $target (使用 lf 或 crlf)"
return 1
;;
esac
return 0
}
# 显示帮助信息
show_help() {
echo "用法: $0 [目录] [格式]"
echo ""
echo "格式:"
echo " lf 转换为 Unix 换行符 (LF) - 默认"
echo " crlf 转换为 Windows 换行符 (CRLF)"
echo ""
echo "示例:"
echo " $0 # 转换当前目录为 LF"
echo " $0 /path/to/dir # 转换指定目录为 LF"
echo " $0 . crlf # 转换当前目录为 CRLF"
echo " $0 /path/to/dir crlf # 转换指定目录为 CRLF"
}
# 主程序
main() {
# 检查参数
if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
show_help
exit 0
fi
if [ ! -d "$TARGET_DIR" ]; then
echo "错误: 目录 '$TARGET_DIR' 不存在"
exit 1
fi
echo "开始处理目录: $TARGET_DIR"
echo "转换格式: $CONVERT_TO"
echo ""
count=0
# 递归查找所有文件
while IFS= read -r -d '' file; do
if convert_file "$file" "$CONVERT_TO"; then
echo "已转换: $file"
((count++))
fi
done < <(find "$TARGET_DIR" -type f -print0)
echo ""
echo "========================================"
echo "处理完成!共转换 $count 个文件"
echo "========================================"
}
# 运行主程序
main
使用方法
Python 版本
# 转换单个文件为 Unix 格式 python3 convert_newlines.py file.txt # 转换单个文件为 Windows 格式 python3 convert_newlines.py file.txt -f crlf # 转换目录中所有 .txt 和 .py 文件 python3 convert_newlines.py /path/to/dir -e .txt .py # 递归处理目录 python3 convert_newlines.py /path/to/dir -r
Windows 批处理版本
- 将脚本保存为
convert_newlines.bat - 双击运行,按照提示输入目录和文件类型
Linux Shell 版本
# 赋予执行权限 chmod +x convert_newlines.sh # 转换当前目录为 Unix 格式 ./convert_newlines.sh # 转换指定目录为 Windows 格式 ./convert_newlines.sh /path/to/dir crlf
注意事项
- 备份重要文件:建议在批量处理前先备份文件
- 二进制文件:脚本会尝试跳过二进制文件
- 编码问题:确保文件编码一致(如 UTF-8)
- 大文件处理:对于非常大的文件,建议使用专门的文件处理工具
选择适合您操作系统的版本即可,Python 版本功能最全面,推荐使用。