scripts/Compare-TextLines.ps1
11.8 KB| 1 | #Requires -Version 7.0 |
| 2 | <# |
| 3 | .SYNOPSIS |
| 4 | 文本文件行级差异对比:逐行比较两个文本文件,列出新增、删除、相同的行。 |
| 5 | |
| 6 | .DESCRIPTION |
| 7 | 常用于核对同一份清单、SOP、配置项的两个版本之间改了什么。 |
| 8 | 默认只在屏幕上输出对比报告,不写任何文件;传 -Output 才另存报告。 |
| 9 | 只读取两个待比较文件,不会修改它们。 |
| 10 | |
| 11 | .PARAMETER Left |
| 12 | 旧版本文件(左侧)。 |
| 13 | |
| 14 | .PARAMETER Right |
| 15 | 新版本文件(右侧)。 |
| 16 | |
| 17 | .PARAMETER Encoding |
| 18 | 读取编码,默认 auto(先看 BOM,再严格尝试 UTF-8,最后按 GB18030 处理)。 |
| 19 | |
| 20 | .PARAMETER TrimLines |
| 21 | 比较时忽略每行首尾空白(显示仍保留原文)。 |
| 22 | |
| 23 | .PARAMETER IgnoreCase |
| 24 | 比较时忽略大小写。 |
| 25 | |
| 26 | .PARAMETER IgnoreBlank |
| 27 | 完全跳过空行和只含空白的行,它们不计入差异。 |
| 28 | |
| 29 | .PARAMETER Context |
| 30 | 每个差异块上下各显示几行相同内容,默认 3。 |
| 31 | |
| 32 | .PARAMETER MaxLines |
| 33 | 参与精细比对时两侧行数的上限,默认 1200。超过时退化为粗粒度对比(先列删除行、再列新增行)。 |
| 34 | |
| 35 | .PARAMETER Output |
| 36 | 把对比报告另存到该文件;不填则只打印到屏幕。 |
| 37 | |
| 38 | .PARAMETER OutputEncoding |
| 39 | 报告文件编码,默认 utf8bom。 |
| 40 | |
| 41 | .EXAMPLE |
| 42 | .\Compare-TextLines.ps1 -Left "D:\清单_旧.txt" -Right "D:\清单_新.txt" |
| 43 | |
| 44 | .EXAMPLE |
| 45 | .\Compare-TextLines.ps1 -Left "D:\SOP_v1.txt" -Right "D:\SOP_v2.txt" -IgnoreBlank -Context 2 -Output "D:\差异报告.txt" |
| 46 | #> |
| 47 | [CmdletBinding()] |
| 48 | param( |
| 49 | [Parameter(Mandatory = $true, Position = 0)] |
| 50 | [string]$Left, |
| 51 | |
| 52 | [Parameter(Mandatory = $true, Position = 1)] |
| 53 | [string]$Right, |
| 54 | |
| 55 | [ValidateSet('auto', 'utf8', 'utf8bom', 'gb18030', 'utf16')] |
| 56 | [string]$Encoding = 'auto', |
| 57 | |
| 58 | [switch]$TrimLines, |
| 59 | |
| 60 | [switch]$IgnoreCase, |
| 61 | |
| 62 | [switch]$IgnoreBlank, |
| 63 | |
| 64 | [ValidateRange(0, 50)] |
| 65 | [int]$Context = 3, |
| 66 | |
| 67 | [ValidateRange(100, 5000)] |
| 68 | [int]$MaxLines = 1200, |
| 69 | |
| 70 | [string]$Output, |
| 71 | |
| 72 | [ValidateSet('utf8', 'utf8bom', 'gb18030', 'utf16')] |
| 73 | [string]$OutputEncoding = 'utf8bom' |
| 74 | ) |
| 75 | |
| 76 | function Read-TextFile([string]$filePath, [string]$encName) { |
| 77 | $bytes = [System.IO.File]::ReadAllBytes($filePath) |
| 78 | if ($encName -eq 'auto') { |
| 79 | if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { |
| 80 | return [System.Text.Encoding]::UTF8.GetString($bytes, 3, $bytes.Length - 3) |
| 81 | } |
| 82 | if ($bytes.Length -ge 2 -and $bytes[0] -eq 0xFF -and $bytes[1] -eq 0xFE) { |
| 83 | return [System.Text.Encoding]::Unicode.GetString($bytes, 2, $bytes.Length - 2) |
| 84 | } |
| 85 | try { |
| 86 | $strict = New-Object System.Text.UTF8Encoding($false, $true) |
| 87 | return $strict.GetString($bytes) |
| 88 | } |
| 89 | catch { } |
| 90 | return ([System.Text.Encoding]::GetEncoding(936)).GetString($bytes) |
| 91 | } |
| 92 | if ($encName -eq 'utf8bom') { |
| 93 | if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { |
| 94 | return [System.Text.Encoding]::UTF8.GetString($bytes, 3, $bytes.Length - 3) |
| 95 | } |
| 96 | return [System.Text.Encoding]::UTF8.GetString($bytes) |
| 97 | } |
| 98 | if ($encName -eq 'utf8') { return [System.Text.Encoding]::UTF8.GetString($bytes) } |
| 99 | if ($encName -eq 'utf16') { |
| 100 | if ($bytes.Length -ge 2 -and $bytes[0] -eq 0xFF -and $bytes[1] -eq 0xFE) { |
| 101 | return [System.Text.Encoding]::Unicode.GetString($bytes, 2, $bytes.Length - 2) |
| 102 | } |
| 103 | return [System.Text.Encoding]::Unicode.GetString($bytes) |
| 104 | } |
| 105 | return ([System.Text.Encoding]::GetEncoding(936)).GetString($bytes) |
| 106 | } |
| 107 | |
| 108 | function Split-Lines([string]$text) { |
| 109 | $arr = [regex]::Split($text, '\r\n|\n|\r') |
| 110 | if ($arr.Count -gt 0 -and [string]::IsNullOrEmpty($arr[$arr.Count - 1])) { |
| 111 | if ($arr.Count -eq 1) { return @() } |
| 112 | return @($arr[0..($arr.Count - 2)]) |
| 113 | } |
| 114 | return @($arr) |
| 115 | } |
| 116 | |
| 117 | function Get-CompareKey([string]$s) { |
| 118 | $k = $s |
| 119 | if ($TrimLines) { $k = $k.Trim() } |
| 120 | if ($IgnoreCase) { $k = $k.ToLowerInvariant() } |
| 121 | return $k |
| 122 | } |
| 123 | |
| 124 | # ---------- 读取 ---------- |
| 125 | foreach ($p in @($Left, $Right)) { |
| 126 | if (-not (Test-Path -LiteralPath $p)) { |
| 127 | Write-Host "错误:文件不存在:$p" |
| 128 | exit 2 |
| 129 | } |
| 130 | if ((Get-Item -LiteralPath $p).PSIsContainer) { |
| 131 | Write-Host "错误:$p 是目录,请指定文本文件。" |
| 132 | exit 2 |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | $leftFull = (Get-Item -LiteralPath $Left).FullName |
| 137 | $rightFull = (Get-Item -LiteralPath $Right).FullName |
| 138 | if ($leftFull -eq $rightFull) { |
| 139 | Write-Host '错误:左右两个参数指向同一个文件,无法比较。' |
| 140 | exit 2 |
| 141 | } |
| 142 | |
| 143 | $leftLines = Split-Lines (Read-TextFile -filePath $leftFull -encName $Encoding) |
| 144 | $rightLines = Split-Lines (Read-TextFile -filePath $rightFull -encName $Encoding) |
| 145 | |
| 146 | # 忽略空行时先过滤 |
| 147 | if ($IgnoreBlank) { |
| 148 | $leftLines = @($leftLines | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) |
| 149 | $rightLines = @($rightLines | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) |
| 150 | } |
| 151 | |
| 152 | $n = $leftLines.Count |
| 153 | $m = $rightLines.Count |
| 154 | $keyL = @($leftLines | ForEach-Object { Get-CompareKey $_ }) |
| 155 | $keyR = @($rightLines | ForEach-Object { Get-CompareKey $_ }) |
| 156 | |
| 157 | # ---------- 去掉公共前后缀,缩小比对范围 ---------- |
| 158 | $prefix = 0 |
| 159 | $minLen = [Math]::Min($n, $m) |
| 160 | while ($prefix -lt $minLen -and $keyL[$prefix] -ceq $keyR[$prefix]) { $prefix++ } |
| 161 | |
| 162 | $suffix = 0 |
| 163 | while ($suffix -lt ($minLen - $prefix) -and |
| 164 | $keyL[$n - 1 - $suffix] -ceq $keyR[$m - 1 - $suffix]) { $suffix++ } |
| 165 | |
| 166 | $nl = $n - $prefix - $suffix |
| 167 | $mr = $m - $prefix - $suffix |
| 168 | |
| 169 | $ops = New-Object 'System.Collections.Generic.List[object]' |
| 170 | |
| 171 | for ($i = 0; $i -lt $prefix; $i++) { |
| 172 | $ops.Add([PSCustomObject]@{ Type = 'equal'; LeftNo = $i + 1; RightNo = $i + 1; Text = $leftLines[$i] }) |
| 173 | } |
| 174 | |
| 175 | $coarse = $false |
| 176 | if ($nl -gt 0 -or $mr -gt 0) { |
| 177 | if ($nl -gt $MaxLines -or $mr -gt $MaxLines) { |
| 178 | # 超大文件:粗粒度处理,先删除后新增 |
| 179 | $coarse = $true |
| 180 | for ($i = 0; $i -lt $nl; $i++) { |
| 181 | $ops.Add([PSCustomObject]@{ Type = 'remove'; LeftNo = $prefix + $i + 1; RightNo = 0; Text = $leftLines[$prefix + $i] }) |
| 182 | } |
| 183 | for ($j = 0; $j -lt $mr; $j++) { |
| 184 | $ops.Add([PSCustomObject]@{ Type = 'add'; LeftNo = 0; RightNo = $prefix + $j + 1; Text = $rightLines[$prefix + $j] }) |
| 185 | } |
| 186 | } |
| 187 | else { |
| 188 | if ($nl -eq 0) { $subL = @() } else { $subL = @($keyL[$prefix..($prefix + $nl - 1)]) } |
| 189 | if ($mr -eq 0) { $subR = @() } else { $subR = @($keyR[$prefix..($prefix + $mr - 1)]) } |
| 190 | |
| 191 | $dp = [Array]::CreateInstance([int], ($nl + 1), ($mr + 1)) |
| 192 | for ($i = $nl - 1; $i -ge 0; $i--) { |
| 193 | for ($j = $mr - 1; $j -ge 0; $j--) { |
| 194 | if ($subL[$i] -ceq $subR[$j]) { |
| 195 | $dp[$i, $j] = $dp[($i + 1), ($j + 1)] + 1 |
| 196 | } |
| 197 | elseif ($dp[($i + 1), $j] -ge $dp[$i, ($j + 1)]) { |
| 198 | $dp[$i, $j] = $dp[($i + 1), $j] |
| 199 | } |
| 200 | else { |
| 201 | $dp[$i, $j] = $dp[$i, ($j + 1)] |
| 202 | } |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | $i = 0 |
| 207 | $j = 0 |
| 208 | while ($i -lt $nl -and $j -lt $mr) { |
| 209 | if ($subL[$i] -ceq $subR[$j]) { |
| 210 | $ops.Add([PSCustomObject]@{ Type = 'equal'; LeftNo = $prefix + $i + 1; RightNo = $prefix + $j + 1; Text = $leftLines[$prefix + $i] }) |
| 211 | $i++ |
| 212 | $j++ |
| 213 | } |
| 214 | elseif ($dp[($i + 1), $j] -ge $dp[$i, ($j + 1)]) { |
| 215 | $ops.Add([PSCustomObject]@{ Type = 'remove'; LeftNo = $prefix + $i + 1; RightNo = 0; Text = $leftLines[$prefix + $i] }) |
| 216 | $i++ |
| 217 | } |
| 218 | else { |
| 219 | $ops.Add([PSCustomObject]@{ Type = 'add'; LeftNo = 0; RightNo = $prefix + $j + 1; Text = $rightLines[$prefix + $j] }) |
| 220 | $j++ |
| 221 | } |
| 222 | } |
| 223 | while ($i -lt $nl) { |
| 224 | $ops.Add([PSCustomObject]@{ Type = 'remove'; LeftNo = $prefix + $i + 1; RightNo = 0; Text = $leftLines[$prefix + $i] }) |
| 225 | $i++ |
| 226 | } |
| 227 | while ($j -lt $mr) { |
| 228 | $ops.Add([PSCustomObject]@{ Type = 'add'; LeftNo = 0; RightNo = $prefix + $j + 1; Text = $rightLines[$prefix + $j] }) |
| 229 | $j++ |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | for ($k = 0; $k -lt $suffix; $k++) { |
| 235 | $ops.Add([PSCustomObject]@{ Type = 'equal'; LeftNo = $prefix + $nl + $k + 1; RightNo = $prefix + $mr + $k + 1; Text = $leftLines[$prefix + $nl + $k] }) |
| 236 | } |
| 237 | |
| 238 | # ---------- 统计 ---------- |
| 239 | $same = 0 |
| 240 | $removed = 0 |
| 241 | $added = 0 |
| 242 | $blocks = 0 |
| 243 | $inBlock = $false |
| 244 | foreach ($op in $ops) { |
| 245 | switch ($op.Type) { |
| 246 | 'equal' { $same++; $inBlock = $false } |
| 247 | 'remove' { $removed++; if (-not $inBlock) { $blocks++; $inBlock = $true } } |
| 248 | 'add' { $added++; if (-not $inBlock) { $blocks++; $inBlock = $true } } |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | # ---------- 生成报告 ---------- |
| 253 | $report = New-Object 'System.Collections.Generic.List[string]' |
| 254 | |
| 255 | $report.Add("旧文件:$leftFull($n 行)") |
| 256 | $report.Add("新文件:$rightFull($m 行)") |
| 257 | if ($coarse) { |
| 258 | $report.Add("提示:行数超过 $MaxLines 的精细比对上限,已退化为粗粒度对比(先列删除、再列新增)。") |
| 259 | } |
| 260 | if ($IgnoreCase) { $report.Add('比较规则:忽略大小写') } |
| 261 | if ($TrimLines) { $report.Add('比较规则:忽略首尾空白') } |
| 262 | if ($IgnoreBlank) { $report.Add('比较规则:跳过空行') } |
| 263 | $report.Add('') |
| 264 | $report.Add("=== 统计 ===") |
| 265 | $report.Add("相同行:$same 删除行:$removed 新增行:$added 差异块:$blocks") |
| 266 | $report.Add('') |
| 267 | $report.Add('=== 差异明细(- 旧文件独有,+ 新文件独有,空格两侧相同) ===') |
| 268 | |
| 269 | $total = $ops.Count |
| 270 | $keep = New-Object 'bool[]' $total |
| 271 | for ($i = 0; $i -lt $total; $i++) { |
| 272 | if ($ops[$i].Type -ne 'equal') { |
| 273 | $s = [Math]::Max(0, $i - $Context) |
| 274 | $e = [Math]::Min($total - 1, $i + $Context) |
| 275 | for ($k = $s; $k -le $e; $k++) { $keep[$k] = $true } |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | $i = 0 |
| 280 | while ($i -lt $total) { |
| 281 | if ($keep[$i]) { |
| 282 | $op = $ops[$i] |
| 283 | switch ($op.Type) { |
| 284 | 'equal' { $report.Add((' {0,5} | {1}' -f $op.LeftNo, $op.Text)) } |
| 285 | 'remove' { $report.Add((' - {0,5} | {1}' -f $op.LeftNo, $op.Text)) } |
| 286 | 'add' { $report.Add((' + {0,5} | {1}' -f $op.RightNo, $op.Text)) } |
| 287 | } |
| 288 | $i++ |
| 289 | } |
| 290 | else { |
| 291 | $start = $i |
| 292 | while ($i -lt $total -and -not $keep[$i]) { $i++ } |
| 293 | $report.Add((' ... 省略 {0} 行相同内容 ...' -f ($i - $start))) |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | if ($blocks -eq 0) { |
| 298 | $report.Add('') |
| 299 | $report.Add('结论:两个文件内容一致,没有差异。') |
| 300 | } |
| 301 | else { |
| 302 | $report.Add('') |
| 303 | $report.Add("结论:共 $blocks 处差异,删除 $removed 行、新增 $added 行。") |
| 304 | } |
| 305 | |
| 306 | # ---------- 输出 ---------- |
| 307 | foreach ($line in $report) { |
| 308 | if ($line -match '^ - ') { Write-Host $line -ForegroundColor Red } |
| 309 | elseif ($line -match '^ \+ ') { Write-Host $line -ForegroundColor Green } |
| 310 | else { Write-Host $line } |
| 311 | } |
| 312 | |
| 313 | if ($Output) { |
| 314 | try { |
| 315 | $outFull = [System.IO.Path]::GetFullPath($Output) |
| 316 | if ($outFull -eq $leftFull -or $outFull -eq $rightFull) { |
| 317 | Write-Host '' |
| 318 | Write-Host '错误:报告路径与待比较文件相同,为避免覆盖已停止写出。' |
| 319 | exit 3 |
| 320 | } |
| 321 | $outDir = [System.IO.Path]::GetDirectoryName($outFull) |
| 322 | if ($outDir -and -not (Test-Path -LiteralPath $outDir)) { |
| 323 | New-Item -ItemType Directory -Force -Path $outDir | Out-Null |
| 324 | } |
| 325 | $encObj = switch ($OutputEncoding) { |
| 326 | 'utf8' { New-Object System.Text.UTF8Encoding($false) } |
| 327 | 'utf8bom' { New-Object System.Text.UTF8Encoding($true) } |
| 328 | 'gb18030' { [System.Text.Encoding]::GetEncoding(936) } |
| 329 | 'utf16' { [System.Text.Encoding]::Unicode } |
| 330 | } |
| 331 | [System.IO.File]::WriteAllText($outFull, ($report -join "`r`n") + "`r`n", $encObj) |
| 332 | Write-Host '' |
| 333 | Write-Host "报告已写出:$outFull" |
| 334 | } |
| 335 | catch { |
| 336 | Write-Host ("写出失败:{0}" -f $_.Exception.Message) |
| 337 | exit 3 |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | if ($blocks -eq 0) { exit 0 } |
| 342 | exit 1 |
文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。

