本文目录导读:

Python脚本 (最灵活)
# 基础替换
import os
# 方法1:单个文件替换
with open('input.txt', 'r', encoding='utf-8') as f:
content = f.read()
content = content.replace('旧文本', '新文本')
content = content.replace('旧文本2', '新文本2')
with open('output.txt', 'w', encoding='utf-8') as f:
f.write(content)
# 方法2:批量处理多个文件
def batch_replace(file_list, old_text, new_text):
for filepath in file_list:
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
content = content.replace(old_text, new_text)
with open(filepath, 'w', encoding='utf-8') as f:
f.write(content)
# 使用方法
files = ['file1.txt', 'file2.txt', 'file3.txt']
batch_replace(files, '旧内容', '新内容')
PowerShell脚本 (Windows)
# 单个文件替换
(Get-Content -Path "input.txt") -replace "旧文本", "新文本" | Set-Content "output.txt"
# 批量替换文件夹内所有txt文件
Get-ChildItem -Path "C:\文件夹" -Filter "*.txt" | ForEach-Object {
$content = Get-Content $_.FullName
$content = $content -replace "旧文本", "新文本"
Set-Content $_.FullName $content
}
Bash脚本 (Linux/Mac)
#!/bin/bash
# 单个文件替换
sed -i 's/旧文本/新文本/g' file.txt
# 批量替换当前目录所有txt文件
for file in *.txt; do
sed -i 's/旧文本/新文本/g' "$file"
done
# 递归替换所有文件
find . -type f -name "*.txt" -exec sed -i 's/旧文本/新文本/g' {} \;
高级Python示例 (带正则)
import re
import os
def advanced_replace(directory, patterns):
"""
patterns: [('旧文本', '新文本'), (r'\d{3}', '数字')]
"""
for filename in os.listdir(directory):
if filename.endswith('.txt'):
filepath = os.path.join(directory, filename)
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
# 应用所有替换规则
for old, new in patterns:
content = re.sub(old, new, content)
with open(filepath, 'w', encoding='utf-8') as f:
f.write(content)
# 使用示例
patterns = [
('旧文本1', '新文本1'),
(r'(\d{3})-(\d{4})', r'\1****\2'), # 隐藏电话号码中间4位
]
advanced_replace('./documents', patterns)
批量替换图形界面工具
- Notepad++: Ctrl+H → "替换" → 点击 "全部替换"
- VS Code: Ctrl+H → 输入新旧文本 → 点击 "全部替换"
- Sublime Text: Ctrl+H → 输入新旧文本 → "Replace All"
实用建议
文件备份
import shutil
def backup_and_replace(filepath, old, new):
# 创建备份
shutil.copy(filepath, filepath + '.bak')
# 执行替换
with open(filepath, 'r') as f:
content = f.read()
content = content.replace(old, new)
with open(filepath, 'w') as f:
f.write(content)
批量处理CSV文件
import csv
def process_csv(filepath, column_index, old, new):
rows = []
with open(filepath, 'r', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
if len(row) > column_index:
row[column_index] = row[column_index].replace(old, new)
rows.append(row)
with open(filepath, 'w', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
writer.writerows(rows)
注意事项
- 测试先行:先在小文件上测试
- 备份重要:操作前先备份文件
- 编码问题:注意文件编码(UTF-8, GBK等)
- 正则转义:使用正则时注意特殊字符转义
需要根据具体的文件格式和替换需求选择合适的方案。