怎么用脚本批量替换文本

wen 实用脚本 1

本文目录导读:

怎么用脚本批量替换文本

  1. Python脚本(最灵活)
  2. 批处理脚本 (Windows)
  3. Shell脚本 (Linux/Mac)
  4. PowerShell脚本 (Windows)
  5. 图形化工具方案
  6. 使用建议

我来介绍几种批量替换文本的方法,从简单到复杂:

Python脚本(最灵活)

基础批量替换

import os
from pathlib import Path
def batch_replace(folder_path, old_text, new_text, file_extensions=['.txt', '.md', '.html']):
    """
    批量替换文件夹中所有指定类型文件中的文本
    """
    folder = Path(folder_path)
    for file_path in folder.rglob('*'):
        # 检查文件扩展名
        if file_path.suffix in file_extensions:
            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}")
# 使用示例
batch_replace('./docs', '旧文本', '新文本')

支持正则表达式的版本

import re
from pathlib import Path
def batch_replace_regex(folder_path, pattern, replacement, file_extensions=['.txt', '.md']):
    """
    使用正则表达式进行批量替换
    """
    folder = Path(folder_path)
    for file_path in folder.rglob('*'):
        if file_path.suffix in file_extensions:
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                # 使用正则表达式替换
                new_content = re.sub(pattern, replacement, content)
                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}")
# 使用示例:替换日期格式
# batch_replace_regex('./files', r'\d{4}-\d{2}-\d{2}', 'YYYY-MM-DD')

批处理脚本 (Windows)

简单文本替换

@echo off
setlocal enabledelayedexpansion
set "search=旧文本"
set "replace=新文本"
for /r "C:\your\folder" %%f in (*.txt) do (
    echo 处理文件: %%f
    powershell -Command "(Get-Content '%%f' -Raw) -replace '%search%', '%replace%' | Set-Content '%%f'"
)
echo 完成!
pause

Shell脚本 (Linux/Mac)

使用sed批量替换

#!/bin/bash
# 批量替换文件夹中所有txt文件的文本
search="旧文本"
replace="新文本"
folder="/path/to/folder"
# 方案1: 递归处理所有txt文件
find "$folder" -name "*.txt" | while read file; do
    echo "处理文件: $file"
    sed -i "s/${search}/${replace}/g" "$file"
done
# 方案2: 使用grep先查找包含目标文本的文件
grep -rl "$search" "$folder" --include="*.txt" | while read file; do
    echo "替换文件: $file"
    sed -i "s/${search}/${replace}/g" "$file"
done

PowerShell脚本 (Windows)

# 批量替换目录下所有文件的文本
$folderPath = "C:\your\folder"
$oldText = "旧文本"
$newText = "新文本"
Get-ChildItem -Path $folderPath -Recurse -Include *.txt, *.md | ForEach-Object {
    Write-Host "处理: $($_.FullName)"
    # 读取内容
    $content = Get-Content $_.FullName -Raw -Encoding UTF8
    # 替换文本
    $newContent = $content.Replace($oldText, $newText)
    # 写入文件
    [System.IO.File]::WriteAllText($_.FullName, $newContent, [System.Text.Encoding]::UTF8)
}
Write-Host "替换完成!"

图形化工具方案

如果不想写脚本,也可以使用这些工具:

  1. Notepad++:Ctrl+H, 勾选"正则表达式",选择"批量替换"
  2. VS Code:Ctrl+Shift+H 全局搜索替换
  3. UEStudio/UltraEdit:支持批量替换
  4. PowerGREP:专业文本处理工具

使用建议

  • 先备份:批量操作前一定要备份原文件
  • 测试运行:先在小范围内测试,确认无误后再批量执行
  • 编码问题:注意文件编码(UTF-8, GBK等)
  • 特殊字符:处理特殊字符时需要转义

你是想替换什么类型的文件?可以告诉我具体场景,我给你针对性的方案。

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