跳到主要内容

line-dedup-sorter-20261118

收藏0

文本行去重与排序工具,对按行排列的文本(名单、清单、日志、配置项等)做去重、排序、去空行、去首尾空白处理,并提供行数与重复数统计,默认只预览不改文件,可选另存为新文件,全程不联网。

让 AI 安装

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

scripts/Dedup-SortLines.ps1

8.8 KB
1#Requires -Version 7.0
2<#
3.SYNOPSIS
4 文本行去重与排序:对文本文件按行做去重、排序、去空行、去首尾空白处理。
5
6.DESCRIPTION
7 常用于清洗清单、日志、名单、配置项等按行排列的文本。
8 默认只在屏幕上预览结果并给出统计,不写任何文件;只有传 -Output 时才另存为新文件。
9 不会覆盖输入文件。
10
11.PARAMETER Path
12 要处理的文本文件路径。
13
14.PARAMETER Encoding
15 读取时使用的编码,默认 auto(自动识别 BOM,再严格尝试 UTF-8,最后按 GB18030 处理)。
16 可选:auto、utf8、utf8bom、gb18030、utf16。
17
18.PARAMETER TrimLines
19 去掉每行首尾的空白字符。
20
21.PARAMETER RemoveEmpty
22 删除空行和只含空白的行。
23
24.PARAMETER IgnoreCase
25 去重和排序时忽略大小写(输出保留首次出现的原始写法)。
26
27.PARAMETER NoDedup
28 只做清理和排序,不去重。
29
30.PARAMETER SortBy
31 排序方式:none 不排序、asc 升序、desc 降序、length 按长度、numeric 按数值。默认 asc。
32
33.PARAMETER Output
34 结果另存到的文件路径。不填则只预览。
35
36.PARAMETER OutputEncoding
37 输出文件编码,默认 utf8bom(Excel、记事本可直接识别)。可选 utf8、utf8bom、gb18030、utf16。
38
39.PARAMETER Preview
40 屏幕上预览多少行,默认 20。设为 0 表示不预览。
41
42.EXAMPLE
43 .\Dedup-SortLines.ps1 -Path "D:\名单.txt"
44
45.EXAMPLE
46 .\Dedup-SortLines.ps1 -Path "D:\名单.txt" -TrimLines -RemoveEmpty -IgnoreCase -Output "D:\名单_去重.txt"
47
48.EXAMPLE
49 .\Dedup-SortLines.ps1 -Path "D:\日志.txt" -SortBy numeric -NoDedup -Output "D:\日志_排序.txt"
50#>
51[CmdletBinding()]
52param(
53 [Parameter(Mandatory = $true, Position = 0)]
54 [string]$Path,
55
56 [ValidateSet('auto', 'utf8', 'utf8bom', 'gb18030', 'utf16')]
57 [string]$Encoding = 'auto',
58
59 [switch]$TrimLines,
60
61 [switch]$RemoveEmpty,
62
63 [switch]$IgnoreCase,
64
65 [switch]$NoDedup,
66
67 [ValidateSet('none', 'asc', 'desc', 'length', 'numeric')]
68 [string]$SortBy = 'asc',
69
70 [string]$Output,
71
72 [ValidateSet('utf8', 'utf8bom', 'gb18030', 'utf16')]
73 [string]$OutputEncoding = 'utf8bom',
74
75 [ValidateRange(0, 5000)]
76 [int]$Preview = 20
77)
78
79function Get-EncodingObject([string]$name, [bool]$forWrite = $false) {
80 switch ($name) {
81 'utf8' { return (New-Object System.Text.UTF8Encoding($false)) }
82 'utf8bom' { return (New-Object System.Text.UTF8Encoding($true)) }
83 'gb18030' { return ([System.Text.Encoding]::GetEncoding(936)) }
84 'utf16' { return ([System.Text.Encoding]::Unicode) }
85 default { return (New-Object System.Text.UTF8Encoding($false)) }
86 }
87}
88
89function Read-TextFile([string]$filePath, [string]$encName) {
90 $bytes = [System.IO.File]::ReadAllBytes($filePath)
91
92 if ($encName -eq 'auto') {
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 if ($bytes.Length -ge 2 -and $bytes[0] -eq 0xFF -and $bytes[1] -eq 0xFE) {
97 return [System.Text.Encoding]::Unicode.GetString($bytes, 2, $bytes.Length - 2)
98 }
99 try {
100 $strict = New-Object System.Text.UTF8Encoding($false, $true)
101 return $strict.GetString($bytes)
102 }
103 catch {
104 # 不是合法 UTF-8,回退到 GB18030
105 }
106 return ([System.Text.Encoding]::GetEncoding(936)).GetString($bytes)
107 }
108
109 if ($encName -eq 'utf8bom') {
110 if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) {
111 return [System.Text.Encoding]::UTF8.GetString($bytes, 3, $bytes.Length - 3)
112 }
113 return [System.Text.Encoding]::UTF8.GetString($bytes)
114 }
115
116 if ($encName -eq 'utf8') {
117 return [System.Text.Encoding]::UTF8.GetString($bytes)
118 }
119
120 if ($encName -eq 'utf16') {
121 if ($bytes.Length -ge 2 -and $bytes[0] -eq 0xFF -and $bytes[1] -eq 0xFE) {
122 return [System.Text.Encoding]::Unicode.GetString($bytes, 2, $bytes.Length - 2)
123 }
124 return [System.Text.Encoding]::Unicode.GetString($bytes)
125 }
126
127 return ([System.Text.Encoding]::GetEncoding(936)).GetString($bytes)
128}
129
130# ---------- 读取 ----------
131if (-not (Test-Path -LiteralPath $Path)) {
132 Write-Host "错误:文件不存在:$Path"
133 exit 2
134}
135
136$fileItem = Get-Item -LiteralPath $Path
137if ($fileItem.PSIsContainer) {
138 Write-Host "错误:$Path 是目录,请指定一个文本文件。"
139 exit 2
140}
141
142$full = $fileItem.FullName
143$text = Read-TextFile -filePath $full -encName $Encoding
144
145if ([string]::IsNullOrWhiteSpace($text)) {
146 Write-Host "提示:文件内容为空,没有可处理的行。"
147 exit 1
148}
149
150$newLine = if ($text.Contains("`r`n")) { "`r`n" } else { "`n" }
151
152$rawLines = [regex]::Split($text, '\r\n|\n|\r')
153if ($rawLines.Count -gt 0 -and $rawLines[-1] -eq '') {
154 $rawLines = $rawLines[0..($rawLines.Count - 2)]
155}
156
157$rawCount = $rawLines.Count
158
159# ---------- 清理与去重 ----------
160$emptyCount = 0
161$seen = New-Object 'System.Collections.Generic.HashSet[string]'
162$outLines = New-Object 'System.Collections.Generic.List[string]'
163$dupCount = 0
164
165foreach ($line in $rawLines) {
166 $work = $line
167 if ($TrimLines) { $work = $work.Trim() }
168
169 if ([string]::IsNullOrWhiteSpace($work)) {
170 $emptyCount++
171 if ($RemoveEmpty) { continue }
172 }
173
174 if (-not $NoDedup) {
175 $key = if ($IgnoreCase) { $work.ToLowerInvariant() } else { $work }
176 if (-not $seen.Add($key)) {
177 $dupCount++
178 continue
179 }
180 }
181
182 $outLines.Add($work)
183}
184
185# ---------- 排序 ----------
186$result = $null
187switch ($SortBy) {
188 'none' {
189 $result = @($outLines)
190 }
191 'asc' {
192 $comparer = if ($IgnoreCase) { [System.StringComparer]::OrdinalIgnoreCase } else { [System.StringComparer]::Ordinal }
193 $arr = @($outLines)
194 [Array]::Sort($arr, $comparer)
195 $result = @($arr)
196 }
197 'desc' {
198 $comparer = if ($IgnoreCase) { [System.StringComparer]::OrdinalIgnoreCase } else { [System.StringComparer]::Ordinal }
199 $arr = @($outLines)
200 [Array]::Sort($arr, $comparer)
201 [Array]::Reverse($arr)
202 $result = @($arr)
203 }
204 'length' {
205 $result = @($outLines | Sort-Object -Property @{ Expression = { $_.Length } }, @{ Expression = { $_ } })
206 }
207 'numeric' {
208 $pairs = @()
209 foreach ($l in $outLines) {
210 $tmp = 0.0
211 $num = if ([double]::TryParse($l.Trim(), [ref]$tmp)) { $tmp } else { [double]::NaN }
212 $pairs += [PSCustomObject]@{ Line = $l; Num = $num }
213 }
214 $sorted = $pairs | Sort-Object -Property @{ Expression = { if ([double]::IsNaN($_.Num)) { [double]::MaxValue } else { $_.Num } } }, @{ Expression = { $_.Line } }
215 $result = @($sorted | ForEach-Object { $_.Line })
216 }
217}
218
219# ---------- 统计 ----------
220Write-Host ''
221Write-Host "=== 统计 ==="
222Write-Host ("源文件:{0}" -f $full)
223Write-Host ("原始行数:{0} 空行:{1} {2}重复行:{3} 输出行数:{4}" -f `
224 $rawCount, $emptyCount, $(if ($RemoveEmpty) { '已删除' } else { '未删除' }), $dupCount, @($result).Count)
225
226# ---------- 预览 ----------
227if ($Preview -gt 0) {
228 Write-Host ''
229 Write-Host ("=== 预览(前 {0} 行) ===" -f $Preview)
230 $show = @($result) | Select-Object -First $Preview
231 $i = 1
232 foreach ($l in $show) {
233 Write-Host ("{0,5} | {1}" -f $i, $l)
234 $i++
235 }
236 if (@($result).Count -gt $Preview) {
237 Write-Host ("…… 还有 {0} 行未显示" -f (@($result).Count - $Preview))
238 }
239}
240
241# ---------- 写出 ----------
242if ($Output) {
243 try {
244 $outFull = [System.IO.Path]::GetFullPath($Output)
245 if ($outFull -eq $full) {
246 Write-Host ''
247 Write-Host '错误:输出路径与源文件相同,为避免覆盖原文件,已停止写出。请换一个输出文件名。'
248 exit 4
249 }
250 $outDir = [System.IO.Path]::GetDirectoryName($outFull)
251 if ($outDir -and -not (Test-Path -LiteralPath $outDir)) {
252 New-Item -ItemType Directory -Force -Path $outDir | Out-Null
253 }
254
255 $sb = New-Object System.Text.StringBuilder
256 foreach ($l in $result) {
257 [void]$sb.Append($l).Append($newLine)
258 }
259 $encObj = Get-EncodingObject -name $OutputEncoding -forWrite $true
260 [System.IO.File]::WriteAllText($outFull, $sb.ToString(), $encObj)
261
262 Write-Host ''
263 Write-Host ("已写出:{0}({1} 行)" -f $outFull, @($result).Count)
264 }
265 catch {
266 Write-Host ("写出失败:{0}" -f $_.Exception.Message)
267 exit 3
268 }
269}
270else {
271 Write-Host ''
272 Write-Host '说明:当前只是预览,未写任何文件。加 -Output 参数可把结果另存为新文件。'
273}
274
275exit 0

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