本帖最后由 zaqmlp 于 2022-4-16 00:26 编辑
- <# :
- cls&echo off&cd /d "%~dp0"
- powershell -NoProfile -ExecutionPolicy bypass "Get-Content -literal \"%~f0\"|out-string|Invoke-Expression"
- pause
- exit
- #>
- $oldcsvfile="原文件.csv";
- $newcsvfile="结果.csv";
- $column=@('7','24') ;
- $len=6;
- if(-not (test-path -literal $oldcsvfile)){write-host ('"'+$oldcsvfile+'" not fount');exit;}
- $enc=[Text.Encoding]::GetEncoding('GB2312');
- $text=[IO.File]::ReadAllText($oldcsvfile, $enc).trim() -split '\r\n';
- $csv=$text[1..($text.Count-1)]|%{$_ -replace '[\r\n]',''}|ConvertFrom-CSV -head @(1..[int]$column[1]|%{$_.ToString()})|select $column;
- $dic=New-Object 'System.Collections.Generic.Dictionary[string, object]';
- foreach($col in $csv){
- $name=$col.($column[0]);
- $detail='';
- $reg='^.{1,'+$len.toString()+'}';
- $m=[regex]::match($col.($column[1]), $reg);
- if($m.Success){
- $detail=$m.groups[0].value;
- if(-not $dic.ContainsKey($detail)){
- [System.Collections.ArrayList]$arr=@();
- $dic.add($detail, @(0, $arr));
- }
- $dic[$detail][0]++;
- if($dic[$detail][1] -notcontains $name){
- [void]$dic[$detail][1].add($name);
- }
- }
- }
- [System.Collections.ArrayList]$s=@();
- $title=@('明细', '数量', '名称') -join ',';
- [void]$s.add($title);
- foreach($k in ($dic.Keys|sort {$dic[$_][0]} -Descending)){
- for($i=0;$i -lt $dic[$k][1].count;$i++){
- $line=@($k, $dic[$k][0].ToString(), $dic[$k][1][$i]) -join ',';
- [void]$s.add($line);
- }
- }
- [IO.File]::WriteAllLines($newcsvfile, $s, $enc);
复制代码
|