[英]PowerShell: Delete similar lines from file
考虑文件tbl.txt
( 150 万行),其构建方式如下:
Num1 ; Num2 ; 'Value' ; 'Attribute'
所以tbl.txt
看起来像:
63 ; 193 ; 'Green' ; 'Color' 152 ; 162 ; 'Tall' ; 'Size' 230 ; 164 ; '130lbs' ; 'Weight' 249 ; 175 ; 'Green' ; 'Color' *duplicate on 'Value' and 'Attribute'* 420 ; 178 ; '8' ; 'Shoesize' 438 ; 172 ; 'Tall' ; 'Size' *duplicate on 'Value' and 'Attribute'*
如何保留'Value'
和'Attribute'
上的第一个唯一行并删除'Value'
和'Attribute'
上'Value'
重复行?
结果应如下所示:
63 ; 193 ; 'Green' ; 'Color' 152 ; 162 ; 'Tall' ; 'Size' 230 ; 164 ; '130lbs' ; 'Weight' 420 ; 178 ; '8' ; 'Shoesize'
任何帮助深表感谢。
假设您的数据没有标题:
Import-CSV "C:\folder\data.txt" –Delimiter ";" -Header Num1,Num2,Value,Attribute | Sort-Object -Property Value -Unique
给出你想要的输出:
Num1 Num2 Value Attribute
---- ---- ----- ---------
230 164 '130lbs' 'Weight'
420 178 '8' 'Shoesize'
63 193 'Green' 'Color'
152 162 'Tall' 'Size'
您可以使用 Export-CSV 导出结果:
Import-CSV "C:\folder\data.txt" –Delimiter ";" -Header Num1,Num2,Value,Attribute | Sort-Object -Property Value -Unique | Export-CSV "C:\folder\data2.txt" –Delimiter ";" -NoTypeInformation
通过Get-Content
循环遍历文本文件,将列'Value' ; 'Attribute'
分开'Value' ; 'Attribute'
'Value' ; 'Attribute'
通过字符串操作,然后使用哈希图来检查您是否已经处理过类似的行——如果没有,则输出该行一次。 在代码中:
$map = @{};
Get-Content tbl.txt | `
%{ $key = $_.Substring($_.IndexOf(';',$_.IndexOf(';')+1)+1); `
If(-not $map.ContainsKey($key)) { $_; $map[$key] = 1 } `
}
或者,如评论中所述,您可以使用group
并应用与分组标准相同的子字符串,最后取每个组的第一个元素:
Get-Content tbl.txt | group {$_.Substring($_.IndexOf(';',$_.IndexOf(';')+1)+1)} `
| %{$_.Group[0]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.