本文目录导读:

Linux/Unix (sed)
# 基本替换(只替换第一个匹配) sed -i 's|/old/path|/new/path|' file.txt # 替换所有匹配 sed -i 's|/old/path|/new/path|g' file.txt # 使用变量 old_path="/var/www/html" new_path="/home/user/www" sed -i "s|$old_path|$new_path|g" file.txt
Perl (更强大)
# 简单替换 perl -pi -e 's|/old/path|/new/path|g' file.txt # 处理特殊字符 perl -pi -e 's|C:\\old\\path|C:\\new\\path|g' config.txt # 备份原文件 perl -pi.bak -e 's|/old/path|/new/path|g' file.txt
Python脚本
#!/usr/bin/env python3
import os
import re
def replace_in_file(filepath, old_path, new_path):
"""
替换文件中的路径
"""
try:
# 读取文件内容
with open(filepath, 'r', encoding='utf-8') as file:
content = file.read()
# 执行替换
new_content = content.replace(old_path, new_path)
# 写回文件
with open(filepath, 'w', encoding='utf-8') as file:
file.write(new_content)
print(f"已更新: {filepath}")
except Exception as e:
print(f"错误处理 {filepath}: {e}")
# 递归替换目录下所有文件
def replace_in_directory(directory, old_path, new_path, extensions=None):
for root, dirs, files in os.walk(directory):
for filename in files:
# 可选:只处理特定扩展名
if extensions and not filename.endswith(extensions):
continue
filepath = os.path.join(root, filename)
replace_in_file(filepath, old_path, new_path)
# 使用示例
if __name__ == "__main__":
# 单个文件
replace_in_file("config.py", "/old/path", "/new/path")
# 递归目录
# replace_in_directory("/project", "/old/path", "/new/path", ('.py', '.conf'))
Python (批量处理+正则)
#!/usr/bin/env python3
import re
import os
def batch_replace_paths(start_dir, replacements, file_pattern=None):
"""
批量替换路径
Args:
start_dir: 起始目录
replacements: 替换规则字典 {旧路径: 新路径}
file_pattern: 文件名模式(如 '*.txt')
"""
for root, dirs, files in os.walk(start_dir):
for filename in files:
# 如果指定了文件模式,则只处理匹配的文件
if file_pattern:
import fnmatch
if not fnmatch.fnmatch(filename, file_pattern):
continue
filepath = os.path.join(root, filename)
try:
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
# 应用所有替换规则
original = content
for old, new in replacements.items():
content = content.replace(old, new)
# 只有当内容有变化时才写回
if content != original:
with open(filepath, 'w', encoding='utf-8') as f:
f.write(content)
print(f"已更新: {filepath}")
except (IOError, UnicodeDecodeError) as e:
print(f"跳过 {filepath}: {e}")
# 使用示例
replacements = {
"/var/www/html": "/home/user/www",
"C:\\old\\project": "D:\\new\\project",
"/app/static": "/app/assets"
}
batch_replace_paths("/my/project", replacements, "*.py")
Windows (PowerShell)
# 简单替换文件中的路径
$file = "config.txt"
$content = Get-Content $file -Raw
$content = $content -replace 'C:\\old\\path', 'D:\\new\\path'
Set-Content $file $content
# 批量处理多个文件
Get-ChildItem "C:\project\*.conf" | ForEach-Object {
$content = Get-Content $_.FullName -Raw
$content = $content -replace '/api/v1', '/api/v2'
Set-Content $_.FullName $content
Write-Host "已更新: $($_.Name)"
}
Node.js脚本
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
function replaceInFile(filePath, oldPath, newPath) {
try {
let content = fs.readFileSync(filePath, 'utf8');
content = content.split(oldPath).join(newPath); // 全局替换
fs.writeFileSync(filePath, content);
console.log(`✓ 已更新: ${filePath}`);
} catch (err) {
console.error(`✗ 错误: ${err.message}`);
}
}
// 批量处理
function batchReplace(directory, oldPath, newPath, extensions) {
const files = fs.readdirSync(directory, { recursive: true });
files.forEach(file => {
const filePath = path.join(directory, file);
const ext = path.extname(filePath);
if (extensions && !extensions.includes(ext)) return;
if (fs.statSync(filePath).isFile()) {
replaceInFile(filePath, oldPath, newPath);
}
});
}
// 使用
batchReplace('./project', '/old/path', '/new/path', ['.py', '.conf', '.cfg']);
Shell脚本(批量备份)
#!/bin/bash
old_path="/old/directory"
new_path="/new/directory"
backup_dir="./backup_$(date +%Y%m%d)"
# 创建备份目录
mkdir -p "$backup_dir"
# 查找并处理文件
find . -type f \( -name "*.conf" -o -name "*.cfg" -o -name "*.py" \) | while read file; do
# 备份原文件
cp "$file" "$backup_dir/${file#./}"
# 执行替换
sed -i "s|$old_path|$new_path|g" "$file"
echo "已更新: $file"
done
echo "备份保存在: $backup_dir"
使用建议
- 备份重要文件:在任何替换操作前先备份
- 测试替换效果:先用
sed 's|old|new|'(不带-i)测试输出 - 处理特殊字符:路径中的需要使用转义
- 编码问题:确保脚本和文件的编码一致(UTF-8)
选择哪种脚本取决于:
- 操作系统(Linux/Windows/Mac)
- 文件数量和类型
- 是否需要递归处理子目录
- 是否需要进行复杂模式匹配