本文目录导读:

Python 脚本(跨平台,推荐)
import os
import re
def find_replace_in_files(root_dir, old_text, new_text, file_extensions=['.txt']):
"""
在指定目录的所有文件中查找并替换文本
"""
for foldername, subfolders, filenames in os.walk(root_dir):
for filename in filenames:
# 检查文件扩展名
if any(filename.endswith(ext) for ext in file_extensions):
file_path = os.path.join(foldername, filename)
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
# 替换文本
new_content = content.replace(old_text, new_text)
if new_content != content:
with open(file_path, 'w', encoding='utf-8') as f:
f.write(new_content)
print(f"已修改: {file_path}")
except Exception as e:
print(f"处理 {file_path} 时出错: {e}")
# 使用示例
find_replace_in_files(
root_dir="./documents", # 要搜索的目录
old_text="foo", # 查找的文本
new_text="bar", # 替换为的文本
file_extensions=['.txt'] # 只处理.txt文件
)
优点:可灵活控制文件类型、支持正则、可添加备份功能
Bash 脚本(Linux/Mac)
#!/bin/bash
# 基本用法
find ./documents -type f -name "*.txt" -exec sed -i 's/foo/bar/g' {} +
# 带正则的版本
find . -type f \( -name "*.txt" -o -name "*.md" \) -exec sed -ri 's/[Ff]oo/Bar/g' {} \;
# 备份原始文件
find . -type f -name "*.txt" -exec sed -i.bak 's/foo/bar/g' {} +
注意:-i 直接修改文件,-i.bak 会创建备份
PowerShell(Windows)
# 基本替换
Get-ChildItem -Path "C:\Documents" -Filter "*.txt" -Recurse | ForEach-Object {
(Get-Content $_.FullName -Raw) -replace 'foo', 'bar' | Set-Content $_.FullName
}
# 带正则和确认
$files = Get-ChildItem -Path "C:\Documents" -Filter "*.txt" -Recurse
foreach ($file in $files) {
$content = Get-Content $file.FullName -Raw
$newContent = $content -replace 'foo\d+', 'bar'
if ($content -ne $newContent) {
Write-Host "修改: $($file.FullName)"
Set-Content $file.FullName -Value $newContent
}
}
安全建议
- 先测试:先用小范围文件测试脚本
- 备份数据:替换前做好文件备份
- 确认编码:处理非UTF-8文件时需指定编码
- 使用正则:注意转义特殊字符(如 表示字面量 )
高级版本(带备份和预览)
import os
import shutil
def safe_find_replace(root_dir, old_text, new_text, preview=True):
"""
安全版:预览或执行替换,自动备份
"""
for root, dirs, files in os.walk(root_dir):
for file in files:
if not file.endswith('.txt'):
continue
path = os.path.join(root, file)
with open(path, 'r', encoding='utf-8') as f:
content = f.read()
if old_text in content:
if preview:
print(f"将修改: {path}")
print(f" 包含: {old_text}")
else:
# 创建备份
backup_path = path + '.bak'
shutil.copy2(path, backup_path)
# 执行替换
new_content = content.replace(old_text, new_text)
with open(path, 'w', encoding='utf-8') as f:
f.write(new_content)
print(f"已修改: {path} (备份: {backup_path})")
# 先预览
safe_find_replace("./docs", "old_text", "new_text", preview=True)
# 确认后执行
safe_find_replace("./docs", "old_text", "new_text", preview=False)
选择建议:
- Python:最灵活,适合复杂逻辑
- Bash/PowerShell:适合快速单次操作
- 带版本:适合重要数据
需要我针对特定场景(如编码问题、二进制文件、目录结构等)调整脚本吗?