怎样用脚本批量替换文件中的字符串?

wen 实用脚本 2

本文目录导读:

怎样用脚本批量替换文件中的字符串?

  1. Linux/macOS 使用 sed 命令
  2. Python 脚本 (跨平台)
  3. PowerShell (Windows)
  4. Perl 脚本 (跨平台)
  5. 高级 Python 脚本(支持正则)
  6. 安全建议
  7. 快速使用命令示例

Linux/macOS 使用 sed 命令

单个文件替换

# 替换文件中的 old_string 为 new_string
sed -i 's/old_string/new_string/g' filename.txt

批量替换当前目录下所有文件

# 替换所有 .txt 文件
sed -i 's/old_string/new_string/g' *.txt
# 递归替换所有文件
find . -type f -exec sed -i 's/old_string/new_string/g' {} +

创建备份文件

# 替换前创建 .bak 备份
sed -i.bak 's/old_string/new_string/g' *.txt

Python 脚本 (跨平台)

import os
import sys
def replace_in_files(directory, old_str, new_str, file_extensions=None):
    """
    批量替换文件中的字符串
    :param directory: 根目录
    :param old_str: 要替换的字符串
    :param new_str: 新字符串
    :param file_extensions: 文件扩展名列表,如 ['.txt', '.py']
    """
    for root, dirs, files in os.walk(directory):
        for filename in files:
            # 如果指定了扩展名,只处理匹配的文件
            if file_extensions:
                ext = os.path.splitext(filename)[1]
                if ext not in file_extensions:
                    continue
            filepath = os.path.join(root, filename)
            try:
                with open(filepath, 'r', encoding='utf-8') as f:
                    content = f.read()
                if old_str in content:
                    new_content = content.replace(old_str, new_str)
                    with open(filepath, 'w', encoding='utf-8') as f:
                        f.write(new_content)
                    print(f"已替换: {filepath}")
            except Exception as e:
                print(f"处理文件 {filepath} 时出错: {e}")
# 使用示例
if __name__ == "__main__":
    # 在指定目录替换所有文件
    replace_in_files("./my_project", "old_text", "new_text")
    # 只替换特定扩展名的文件
    replace_in_files("./my_project", "old_text", "new_text", ['.txt', '.html', '.js'])

PowerShell (Windows)

# 替换当前目录所有 .txt 文件
Get-ChildItem -Path . -Filter *.txt -Recurse | ForEach-Object {
    (Get-Content $_.FullName) -replace 'old_string', 'new_string' | Set-Content $_.FullName
}
# 带参数版本
param(
    [string]$Path = ".",
    [string]$OldString = "old",
    [string]$NewString = "new",
    [string]$Extension = "*"
)
Get-ChildItem -Path $Path -Filter "*.$Extension" -Recurse | ForEach-Object {
    $content = Get-Content $_.FullName -Raw
    $content -replace $OldString, $NewString | Out-File $_.FullName -Encoding UTF8
}

Perl 脚本 (跨平台)

# 批量替换并创建备份
perl -i.bak -pe 's/old_string/new_string/g' *.txt
# 递归替换
find . -name "*.txt" -exec perl -i -pe 's/old_string/new_string/g' {} \;

高级 Python 脚本(支持正则)

import os
import re
def advanced_replace(directory, pattern, replacement, file_extensions=None, use_regex=True):
    """
    高级替换功能,支持正则表达式
    """
    compiled_pattern = re.compile(pattern) if use_regex else None
    for root, dirs, files in os.walk(directory):
        # 跳过 .git 等目录
        dirs[:] = [d for d in dirs if not d.startswith('.')]
        for filename in files:
            # 跳过二进制文件和临时文件
            if filename.endswith(('.pyc', '.bak', '.swp')):
                continue
            if file_extensions:
                ext = os.path.splitext(filename)[1]
                if ext not in file_extensions:
                    continue
            filepath = os.path.join(root, filename)
            try:
                with open(filepath, 'r', encoding='utf-8') as f:
                    content = f.read()
                if use_regex:
                    new_content, count = compiled_pattern.subn(replacement, content)
                else:
                    new_content = content.replace(pattern, replacement)
                    count = content.count(pattern)
                if count > 0:
                    with open(filepath, 'w', encoding='utf-8') as f:
                        f.write(new_content)
                    print(f"已替换 {count} 处: {filepath}")
            except Exception as e:
                print(f"跳过文件 {filepath}: {e}")
# 使用示例
advanced_replace(
    "./project", 
    r"old_\w+",  # 正则匹配
    "new_value",
    file_extensions=['.txt', '.html'],
    use_regex=True
)

安全建议

  1. 先测试:在正式运行前,先用小范围文件测试
  2. 备份数据:重要文件先备份
  3. 使用版本控制:在 Git 等版本控制环境中操作
  4. 注意编码:确保文件编码(UTF-8、GBK等)正确

快速使用命令示例

# Linux/macOS - 替换所有 html 文件中的域名
sed -i 's/old-domain.com/new-domain.com/g' *.html
# Python - 简单一行命令
python -c "
import os
for f in os.listdir('.'):
    if f.endswith('.txt'):
        with open(f,'r+') as file:
            content = file.read().replace('old','new')
            file.seek(0)
            file.write(content)
            file.truncate()
"

根据您的操作系统和具体需求选择合适的方案,对于简单的任务,sed 命令最快捷;对于复杂的替换逻辑,Python 更灵活。

抱歉,评论功能暂时关闭!