scripts/Split-TextFile.ps1
12.8 KB| 1 | #Requires -Version 7.0 |
| 2 | <# |
| 3 | .SYNOPSIS |
| 4 | 按行数或体积把一个大文本文件切成多个小文件,可选每片重复表头。 |
| 5 | |
| 6 | .DESCRIPTION |
| 7 | 用于把超大的日志、CSV、导出清单切分成便于打开、上传、分发的多个分片。 |
| 8 | 默认只做预估(预览),加 -Apply 才真正写出分片;不修改源文件。 |
| 9 | 自动识别 UTF-8(含/不含 BOM)、UTF-16、GB18030 编码,并保留源文件的换行风格。 |
| 10 | |
| 11 | .PARAMETER Path |
| 12 | 待切分的源文件路径(必填)。 |
| 13 | |
| 14 | .PARAMETER LinesPerChunk |
| 15 | 每个分片最多包含的数据行数,1~1000000,默认 1000。 |
| 16 | |
| 17 | .PARAMETER MaxChunkMB |
| 18 | 每个分片的体积上限(MB),0~500,默认 0 表示不限制。两个上限同时生效,先到者为准。 |
| 19 | |
| 20 | .PARAMETER OutDir |
| 21 | 分片输出目录,默认在源文件同级的 <文件名>_parts 目录。 |
| 22 | |
| 23 | .PARAMETER Prefix |
| 24 | 分片文件名前缀,默认取源文件名(不含扩展名)。 |
| 25 | |
| 26 | .PARAMETER KeepHeader |
| 27 | 把首行(跳过 -SkipLines 之后的第一行)当作表头,每个分片首行都重复一次,表头不计入行数上限。适合 CSV。 |
| 28 | |
| 29 | .PARAMETER SkipLines |
| 30 | 跳过源文件开头的 N 行(如导出说明、多行注释),默认 0。 |
| 31 | |
| 32 | .PARAMETER Encoding |
| 33 | 源文件编码:auto(默认自动识别)、utf8、utf8bom、gb18030、utf16。 |
| 34 | |
| 35 | .PARAMETER OutputEncoding |
| 36 | 分片文件编码:auto(默认跟随源文件)、utf8、utf8bom、gb18030、utf16。 |
| 37 | |
| 38 | .PARAMETER Digits |
| 39 | 分片序号位数,2~6,默认 3(即 part001)。 |
| 40 | |
| 41 | .PARAMETER Apply |
| 42 | 真正写出分片文件。不加此开关时只输出预估结果,不写任何文件。 |
| 43 | |
| 44 | .PARAMETER Force |
| 45 | 目标分片已存在时覆盖。默认遇到同名文件跳过该分片并提示。 |
| 46 | |
| 47 | .EXAMPLE |
| 48 | pwsh -File Split-TextFile.ps1 -Path .\server.log -LinesPerChunk 2000 |
| 49 | 预估日志按每片 2000 行切分成几片。 |
| 50 | |
| 51 | .EXAMPLE |
| 52 | pwsh -File Split-TextFile.ps1 -Path .\supplier.csv -LinesPerChunk 500 -KeepHeader -Apply |
| 53 | 把清单按每片 500 条数据行切分,每片都带表头。 |
| 54 | |
| 55 | .NOTES |
| 56 | 退出码:0 成功;2 输入或参数有问题;3 写出失败。 |
| 57 | #> |
| 58 | [CmdletBinding()] |
| 59 | param( |
| 60 | [Parameter(Mandatory = $true)] |
| 61 | [string]$Path, |
| 62 | |
| 63 | [int]$LinesPerChunk = 1000, |
| 64 | |
| 65 | [double]$MaxChunkMB = 0, |
| 66 | |
| 67 | [string]$OutDir = '', |
| 68 | |
| 69 | [string]$Prefix = '', |
| 70 | |
| 71 | [switch]$KeepHeader, |
| 72 | |
| 73 | [int]$SkipLines = 0, |
| 74 | |
| 75 | [ValidateSet('auto', 'utf8', 'utf8bom', 'gb18030', 'utf16')] |
| 76 | [string]$Encoding = 'auto', |
| 77 | |
| 78 | [ValidateSet('auto', 'utf8', 'utf8bom', 'gb18030', 'utf16')] |
| 79 | [string]$OutputEncoding = 'auto', |
| 80 | |
| 81 | [ValidateRange(2, 6)] |
| 82 | [int]$Digits = 3, |
| 83 | |
| 84 | [switch]$Apply, |
| 85 | |
| 86 | [switch]$Force |
| 87 | ) |
| 88 | |
| 89 | $ErrorActionPreference = 'Stop' |
| 90 | |
| 91 | function Write-Fail([string]$msg, [int]$code) { |
| 92 | [Console]::Error.WriteLine($msg) |
| 93 | exit $code |
| 94 | } |
| 95 | |
| 96 | function Get-FileEncoding([string]$filePath) { |
| 97 | $fs = [System.IO.File]::Open($filePath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read) |
| 98 | try { |
| 99 | $buf = New-Object byte[] 4 |
| 100 | $read = $fs.Read($buf, 0, 4) |
| 101 | } |
| 102 | finally { $fs.Dispose() } |
| 103 | |
| 104 | if ($read -ge 3 -and $buf[0] -eq 0xEF -and $buf[1] -eq 0xBB -and $buf[2] -eq 0xBF) { return 'utf8bom' } |
| 105 | if ($read -ge 2 -and $buf[0] -eq 0xFF -and $buf[1] -eq 0xFE) { return 'utf16' } |
| 106 | if ($read -ge 2 -and $buf[0] -eq 0xFE -and $buf[1] -eq 0xFF) { return 'utf16' } |
| 107 | |
| 108 | # 用增量 Decoder 校验,可容忍块尾被截断的多字节字符,避免误判为 GB18030 |
| 109 | $strict = [System.Text.UTF8Encoding]::new($false, $true) |
| 110 | $dec = $strict.GetDecoder() |
| 111 | $buf2 = New-Object byte[] 1048576 |
| 112 | $chars = New-Object char[] 1048584 |
| 113 | $fs2 = [System.IO.File]::Open($filePath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read) |
| 114 | try { |
| 115 | while (($n = $fs2.Read($buf2, 0, $buf2.Length)) -gt 0) { |
| 116 | try { [void]$dec.GetChars($buf2, 0, $n, $chars, 0) } |
| 117 | catch { return 'gb18030' } |
| 118 | } |
| 119 | } |
| 120 | finally { $fs2.Dispose() } |
| 121 | |
| 122 | return 'utf8' |
| 123 | } |
| 124 | |
| 125 | function New-TextEncoding([string]$name) { |
| 126 | switch ($name) { |
| 127 | 'utf8' { return [System.Text.UTF8Encoding]::new($false) } |
| 128 | 'utf8bom' { return [System.Text.UTF8Encoding]::new($true) } |
| 129 | 'utf16' { return [System.Text.UnicodeEncoding]::new($false, $true) } |
| 130 | 'gb18030' { return [System.Text.Encoding]::GetEncoding(54936) } |
| 131 | default { return [System.Text.UTF8Encoding]::new($false) } |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | function Get-NewLineStyle([string]$filePath, [System.Text.Encoding]$enc) { |
| 136 | $probe = [System.IO.StreamReader]::new($filePath, $enc, $true) |
| 137 | try { |
| 138 | $chars = New-Object char[] 400 |
| 139 | $n = $probe.Read($chars, 0, 400) |
| 140 | } |
| 141 | finally { $probe.Dispose() } |
| 142 | if ($n -le 0) { return @{ Style = 'LF'; Text = "`n" } } |
| 143 | |
| 144 | $head = [string]::new($chars, 0, $n) |
| 145 | if ($head.Contains("`r`n")) { return @{ Style = 'CRLF'; Text = "`r`n" } } |
| 146 | if ($head.Contains("`n")) { return @{ Style = 'LF'; Text = "`n" } } |
| 147 | if ($head.Contains("`r")) { return @{ Style = 'CR'; Text = "`r" } } |
| 148 | return @{ Style = 'LF'; Text = "`n" } |
| 149 | } |
| 150 | |
| 151 | # ---------- 参数校验 ---------- |
| 152 | if (-not (Test-Path -LiteralPath $Path)) { Write-Fail "文件不存在:$Path" 2 } |
| 153 | $item = Get-Item -LiteralPath $Path |
| 154 | if ($item.PSIsContainer) { Write-Fail "路径是目录而不是文件:$Path" 2 } |
| 155 | if ($item.Length -eq 0) { Write-Fail "源文件为空,没有可切分的内容:$Path" 2 } |
| 156 | if ($LinesPerChunk -lt 1 -or $LinesPerChunk -gt 1000000) { Write-Fail '-LinesPerChunk 需在 1~1000000 之间' 2 } |
| 157 | if ($MaxChunkMB -lt 0 -or $MaxChunkMB -gt 500) { Write-Fail '-MaxChunkMB 需在 0~500 之间(0 表示不限)' 2 } |
| 158 | if ($SkipLines -lt 0) { Write-Fail '-SkipLines 不能为负数' 2 } |
| 159 | |
| 160 | $srcEncName = if ($Encoding -eq 'auto') { Get-FileEncoding $Path } else { $Encoding } |
| 161 | $outEncName = if ($OutputEncoding -eq 'auto') { $srcEncName } else { $OutputEncoding } |
| 162 | $srcEnc = New-TextEncoding $srcEncName |
| 163 | $outEnc = New-TextEncoding $outEncName |
| 164 | |
| 165 | $nl = Get-NewLineStyle $item.FullName $srcEnc |
| 166 | $newLine = $nl.Text |
| 167 | |
| 168 | if ([string]::IsNullOrWhiteSpace($OutDir)) { |
| 169 | $OutDir = Join-Path $item.DirectoryName ($item.BaseName + '_parts') |
| 170 | } |
| 171 | if ([string]::IsNullOrWhiteSpace($Prefix)) { $Prefix = $item.BaseName } |
| 172 | |
| 173 | $ext = $item.Extension |
| 174 | if ([string]::IsNullOrWhiteSpace($ext)) { $ext = '.txt' } |
| 175 | |
| 176 | $fullOut = [System.IO.Path]::GetFullPath($OutDir).TrimEnd('\', '/') |
| 177 | $fullSrcDir = [System.IO.Path]::GetFullPath($item.DirectoryName).TrimEnd('\', '/') |
| 178 | if ($fullOut -eq $fullSrcDir) { |
| 179 | Write-Fail '输出目录不能与源文件所在目录相同,请用 -OutDir 指定单独目录' 2 |
| 180 | } |
| 181 | |
| 182 | if ($Apply) { |
| 183 | try { |
| 184 | if (-not (Test-Path -LiteralPath $OutDir)) { New-Item -ItemType Directory -Path $OutDir -Force | Out-Null } |
| 185 | } |
| 186 | catch { Write-Fail ("无法创建输出目录:{0} —— {1}" -f $OutDir, $_.Exception.Message) 3 } |
| 187 | if (-not (Test-Path -LiteralPath $OutDir)) { Write-Fail ("输出目录不可用:{0}" -f $OutDir) 3 } |
| 188 | } |
| 189 | |
| 190 | # ---------- 读取并切分 ---------- |
| 191 | $chunkIndex = 0 |
| 192 | $totalLines = 0 |
| 193 | $dataLines = 0 |
| 194 | $skipped = 0 |
| 195 | $headerLine = $null |
| 196 | $chunkStats = [System.Collections.Generic.List[object]]::new() |
| 197 | $written = 0 |
| 198 | $skippedExisting = 0 |
| 199 | $pending = [System.Collections.Generic.List[string]]::new() |
| 200 | $currentBytes = 0 |
| 201 | $byteLimit = if ($MaxChunkMB -gt 0) { [long]($MaxChunkMB * 1MB) } else { [long]0 } |
| 202 | |
| 203 | $reader = [System.IO.StreamReader]::new($item.FullName, $srcEnc, $true) |
| 204 | try { |
| 205 | while ($null -ne ($line = $reader.ReadLine())) { |
| 206 | $totalLines++ |
| 207 | |
| 208 | if ($skipped -lt $SkipLines) { $skipped++; continue } |
| 209 | |
| 210 | if ($KeepHeader -and $null -eq $headerLine) { |
| 211 | $headerLine = $line |
| 212 | if ($byteLimit -gt 0) { $byteLimit -= ($outEnc.GetByteCount($headerLine) + $outEnc.GetByteCount($newLine)) } |
| 213 | continue |
| 214 | } |
| 215 | |
| 216 | $dataLines++ |
| 217 | $lineBytes = $outEnc.GetByteCount($line) + $outEnc.GetByteCount($newLine) |
| 218 | |
| 219 | if ($byteLimit -gt 0 -and $pending.Count -gt 0 -and ($currentBytes + $lineBytes) -gt $byteLimit) { |
| 220 | # 落盘当前分片 |
| 221 | $chunkIndex++ |
| 222 | $name = '{0}.part{1}{2}' -f $Prefix, $chunkIndex.ToString("D$Digits"), $ext |
| 223 | $outPath = Join-Path $OutDir $name |
| 224 | $chunkStats.Add([pscustomobject]@{ Index = $chunkIndex; File = $name; Lines = $pending.Count; Bytes = $currentBytes; Path = $outPath }) |
| 225 | |
| 226 | if ($Apply) { |
| 227 | if ((Test-Path -LiteralPath $outPath) -and -not $Force) { |
| 228 | $skippedExisting++ |
| 229 | [Console]::Error.WriteLine("跳过已存在文件(未加 -Force):$name") |
| 230 | } |
| 231 | else { |
| 232 | $sw = [System.IO.StreamWriter]::new($outPath, $false, $outEnc) |
| 233 | try { |
| 234 | if ($KeepHeader -and $null -ne $headerLine) { $sw.Write($headerLine + $newLine) } |
| 235 | foreach ($l in $pending) { $sw.Write($l + $newLine) } |
| 236 | } |
| 237 | finally { $sw.Dispose() } |
| 238 | $written++ |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | $pending = [System.Collections.Generic.List[string]]::new() |
| 243 | $currentBytes = 0 |
| 244 | } |
| 245 | |
| 246 | $pending.Add($line) |
| 247 | $currentBytes += $lineBytes |
| 248 | |
| 249 | if ($pending.Count -ge $LinesPerChunk) { |
| 250 | $chunkIndex++ |
| 251 | $name = '{0}.part{1}{2}' -f $Prefix, $chunkIndex.ToString("D$Digits"), $ext |
| 252 | $outPath = Join-Path $OutDir $name |
| 253 | $chunkStats.Add([pscustomobject]@{ Index = $chunkIndex; File = $name; Lines = $pending.Count; Bytes = $currentBytes; Path = $outPath }) |
| 254 | |
| 255 | if ($Apply) { |
| 256 | if ((Test-Path -LiteralPath $outPath) -and -not $Force) { |
| 257 | $skippedExisting++ |
| 258 | [Console]::Error.WriteLine("跳过已存在文件(未加 -Force):$name") |
| 259 | } |
| 260 | else { |
| 261 | $sw = [System.IO.StreamWriter]::new($outPath, $false, $outEnc) |
| 262 | try { |
| 263 | if ($KeepHeader -and $null -ne $headerLine) { $sw.Write($headerLine + $newLine) } |
| 264 | foreach ($l in $pending) { $sw.Write($l + $newLine) } |
| 265 | } |
| 266 | finally { $sw.Dispose() } |
| 267 | $written++ |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | $pending = [System.Collections.Generic.List[string]]::new() |
| 272 | $currentBytes = 0 |
| 273 | } |
| 274 | } |
| 275 | } |
| 276 | finally { $reader.Dispose() } |
| 277 | |
| 278 | # 剩余尾巴 |
| 279 | if ($pending.Count -gt 0) { |
| 280 | $chunkIndex++ |
| 281 | $name = '{0}.part{1}{2}' -f $Prefix, $chunkIndex.ToString("D$Digits"), $ext |
| 282 | $outPath = Join-Path $OutDir $name |
| 283 | $chunkStats.Add([pscustomobject]@{ Index = $chunkIndex; File = $name; Lines = $pending.Count; Bytes = $currentBytes; Path = $outPath }) |
| 284 | |
| 285 | if ($Apply) { |
| 286 | if ((Test-Path -LiteralPath $outPath) -and -not $Force) { |
| 287 | $skippedExisting++ |
| 288 | [Console]::Error.WriteLine("跳过已存在文件(未加 -Force):$name") |
| 289 | } |
| 290 | else { |
| 291 | $sw = [System.IO.StreamWriter]::new($outPath, $false, $outEnc) |
| 292 | try { |
| 293 | if ($KeepHeader -and $null -ne $headerLine) { $sw.Write($headerLine + $newLine) } |
| 294 | foreach ($l in $pending) { $sw.Write($l + $newLine) } |
| 295 | } |
| 296 | finally { $sw.Dispose() } |
| 297 | $written++ |
| 298 | } |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | # ---------- 报告 ---------- |
| 303 | Write-Host '' |
| 304 | Write-Host '==== 文本文件切分 ====' |
| 305 | Write-Host ("源文件 : {0}" -f $item.FullName) |
| 306 | Write-Host ("源文件大小 : {0:N1} KB" -f ($item.Length / 1KB)) |
| 307 | Write-Host ("编码 : {0}(输出 {1})" -f $srcEncName, $outEncName) |
| 308 | Write-Host ("换行风格 : {0}" -f $nl.Style) |
| 309 | Write-Host ("总行数 : {0}" -f $totalLines) |
| 310 | if ($SkipLines -gt 0) { Write-Host ("跳过开头行 : {0}" -f $skipped) } |
| 311 | if ($KeepHeader) { |
| 312 | if ($null -ne $headerLine) { Write-Host ("重复表头 : {0}" -f $headerLine) } |
| 313 | else { Write-Host '重复表头 : 未取到表头(文件行数不足)' } |
| 314 | } |
| 315 | Write-Host ("待切分数据行 : {0}" -f $dataLines) |
| 316 | Write-Host ("每片行数上限 : {0}" -f $LinesPerChunk) |
| 317 | Write-Host ("每片体积上限 : {0}" -f $(if ($MaxChunkMB -gt 0) { "$MaxChunkMB MB" } else { '不限' })) |
| 318 | Write-Host ("分片数量 : {0}" -f $chunkIndex) |
| 319 | Write-Host '' |
| 320 | |
| 321 | if ($chunkStats.Count -gt 0) { |
| 322 | Write-Host '序号 分片文件 行数 大小(KB)' |
| 323 | Write-Host '---- ---------------------------- ------- ---------' |
| 324 | foreach ($s in $chunkStats) { |
| 325 | Write-Host ("{0,4} {1,-28} {2,7} {3,9:N1}" -f $s.Index, $s.File, $s.Lines, ($s.Bytes / 1KB)) |
| 326 | } |
| 327 | Write-Host '' |
| 328 | } |
| 329 | |
| 330 | if ($Apply) { |
| 331 | Write-Host ("已写出分片 : {0} 个" -f $written) |
| 332 | if ($skippedExisting -gt 0) { Write-Host ("跳过已存在 : {0} 个(加 -Force 可覆盖)" -f $skippedExisting) } |
| 333 | Write-Host ("输出目录 : {0}" -f $OutDir) |
| 334 | if ($written -eq 0 -and $skippedExisting -gt 0) { Write-Fail '没有写出任何分片(同名文件已存在)' 3 } |
| 335 | } |
| 336 | else { |
| 337 | Write-Host '当前为预览模式,未写出任何文件。确认无误后加 -Apply 执行。' |
| 338 | Write-Host ("预计输出目录 : {0}" -f $OutDir) |
| 339 | } |
| 340 | |
| 341 | exit 0 |
文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。

