跳到主要内容

batch-text-replacer-20261116

收藏0

本地离线批量文本替换工具,按字面或正则在一个目录下的多个文本文件中查找替换内容,默认试运行只报告命中数量,确认后加 -Apply 才真正写入并自动生成 .bak 备份,保留原文件编码与换行风格,全程不联网。

让 AI 安装

MercuryLV2最新版本 0.1.0更新于 2026-11-16下载 0 次

scripts/Replace-Text.ps1

4.9 KB
1#Requires -Version 7.0
2<#
3.SYNOPSIS
4 批量文本查找替换(默认试运行)。
5#>
6[CmdletBinding()]
7param(
8 [Parameter(Mandatory = $true)]
9 [string]$Path,
10
11 [Parameter(Mandatory = $true)]
12 [string]$Pattern,
13
14 [Parameter(Mandatory = $true)]
15 [AllowEmptyString()]
16 [string]$ReplaceWith,
17
18 [switch]$Regex,
19 [string]$Include = "*.txt,*.md,*.csv,*.log,*.json,*.ini",
20 [switch]$Apply,
21 [switch]$IgnoreCase,
22 [switch]$NoBackup,
23 [ValidateSet("utf8", "utf8bom", "gb18030", "utf16")]
24 [string]$Encoding = "utf8"
25)
26
27$ErrorActionPreference = "Stop"
28
29function Get-Encoder([string]$name) {
30 switch ($name) {
31 "utf8" { return New-Object System.Text.UTF8Encoding($false) }
32 "utf8bom" { return New-Object System.Text.UTF8Encoding($true) }
33 "gb18030" { return [System.Text.Encoding]::GetEncoding(54936) }
34 "utf16" { return New-Object System.Text.UnicodeEncoding($false, $true) }
35 default { throw "不支持的编码:$name" }
36 }
37}
38
39function Get-TargetFiles([string]$targetPath, [string]$includePatterns) {
40 if (Test-Path -LiteralPath $targetPath -PathType Leaf) {
41 return @((Get-Item -LiteralPath $targetPath).FullName)
42 }
43 if (-not (Test-Path -LiteralPath $targetPath -PathType Container)) {
44 throw "路径不存在:$targetPath"
45 }
46
47 $patterns = @($includePatterns -split "," | Where-Object { $_.Trim() -ne "" } | ForEach-Object { $_.Trim() })
48 $list = New-Object System.Collections.Generic.List[string]
49 foreach ($pattern in $patterns) {
50 $found = @(Get-ChildItem -LiteralPath $targetPath -Recurse -File -Filter $pattern -Force)
51 foreach ($file in $found) {
52 $list.Add($file.FullName)
53 }
54 }
55 return @($list | Sort-Object -Unique)
56}
57
58function Test-HasBom([byte[]]$bytes) {
59 return ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF)
60}
61
62if ($Pattern.Length -eq 0) {
63 Write-Error "Pattern 不能为空"
64 exit 2
65}
66
67try {
68 $files = @(Get-TargetFiles $Path $Include)
69}
70catch {
71 Write-Host "错误:$($_.Exception.Message)"
72 exit 2
73}
74if ($files.Count -eq 0) {
75 Write-Host "提示:在 $Path 下未找到匹配 $Include 的文件"
76 exit 1
77}
78
79$options = if ($IgnoreCase) { [System.Text.RegularExpressions.RegexOptions]::IgnoreCase } else { [System.Text.RegularExpressions.RegexOptions]::None }
80$matchExpression = if ($Regex) { $Pattern } else { [System.Text.RegularExpressions.Regex]::Escape($Pattern) }
81$baseEncoder = Get-Encoder $Encoding
82
83$mode = if ($Apply) { "替换" } else { "预览" }
84$changedFiles = 0
85$totalHits = 0
86$failed = 0
87$skipped = 0
88
89foreach ($file in $files) {
90 try {
91 $bytes = [System.IO.File]::ReadAllBytes($file)
92 $hasBom = Test-HasBom $bytes
93
94 # StreamReader 自动识别并剥离 BOM,避免文件开头混入 U+FEFF 字符
95 $reader = New-Object System.IO.StreamReader($file, $baseEncoder, $true)
96 try {
97 $content = $reader.ReadToEnd()
98 }
99 finally {
100 $reader.Dispose()
101 }
102
103 $matches = @([System.Text.RegularExpressions.Regex]::Matches($content, $matchExpression, $options))
104 $hitCount = $matches.Count
105
106 if ($hitCount -eq 0) {
107 Write-Host "[跳过] $file :无命中"
108 $skipped++
109 continue
110 }
111
112 if ($Regex) {
113 $newContent = [System.Text.RegularExpressions.Regex]::Replace($content, $Pattern, $ReplaceWith, $options)
114 }
115 else {
116 $evaluator = [System.Text.RegularExpressions.MatchEvaluator] { param($m) $ReplaceWith }
117 $newContent = [System.Text.RegularExpressions.Regex]::Replace($content, $matchExpression, $evaluator, $options)
118 }
119
120 if ($Apply) {
121 if (-not $NoBackup) {
122 $backupPath = "$file.bak"
123 if (-not (Test-Path -LiteralPath $backupPath)) {
124 Copy-Item -LiteralPath $file -Destination $backupPath -Force
125 }
126 }
127 $writeEncoder = if ($Encoding -eq "utf8" -and $hasBom) { New-Object System.Text.UTF8Encoding($true) } else { $baseEncoder }
128 [System.IO.File]::WriteAllText($file, $newContent, $writeEncoder)
129 Write-Host "[已替换] $file :命中 $hitCount 处"
130 }
131 else {
132 Write-Host "[预览] $file :命中 $hitCount 处"
133 }
134
135 $changedFiles++
136 $totalHits += $hitCount
137 }
138 catch {
139 Write-Host "[失败] $file :$($_.Exception.Message)"
140 $failed++
141 }
142}
143
144Write-Host ""
145Write-Host ("{0}完成:扫描 {1} 个文件,{2} 个待改/已改,{3} 个无命中,{4} 个失败,共命中 {5} 处" -f `
146 $mode, $files.Count, $changedFiles, $skipped, $failed, $totalHits)
147if (-not $Apply -and $changedFiles -gt 0) {
148 Write-Host "当前为预览模式,确认无误后加 -Apply 才会真正写入(会生成 .bak 备份)。"
149}
150
151if ($failed -gt 0) { exit 1 } else { exit 0 }

文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。