首页 > 解决方案 > 识别列表中不止一次存在的所有项目并将它们全部列出

问题描述

我有一个列表,其中重复了几个项目。我需要识别这些项目并创建一个新列表以包含所有重复的项目,但每次它们再次出现。

这是列表:

apple
orange
pear
carrot
tomato
cucumber
apple
apple
apple
cucumber
tomato

那是苹果x4,番茄x2,黄瓜x2,其余x1。

所需的新列表将是:

apple
apple
apple
apple
tomato
tomato
cucumber
cucumber

这省略了只存在一次的那些,并列出了不止一次存在的那些,并且每次出现。

我努力了:

$Fruits = Get-Content -Path C:\temp\Fruits.txt

$Unique = $Fruits | Select-Object -Unique
$MoreThanOne = Compare-Object –referenceobject $Unique –differenceobject $Fruits | Select-Object -ExpandProperty inputobject

$MoreThanOne

这会产生:

apple
apple
apple
cucumber
tomato

每个水果都缺少一个。

请问有什么想法吗?

标签: powershell

解决方案


通过比较两个对象并保存差异,您基本上可以执行($Unique - "each entry once"). 这是因为您想要保存所有条目的变量和保存每个条目一次的变量之间的差异。

对此提供了更好的解决方案Group-Object。这会将所有条目组合在一起,以便您可以查找具有多个条目的条目。

命令Get-Content -Path C:\temp\Fruits.txt | Group-Object输出:

Count Name                      Group
----- ----                      -----
    4 apple                     {apple, apple, apple, apple}
    2 tomato                    {tomato, tomato}
    2 cucumber                  {cucumber, cucumber}
    1 carrot                    {carrot}
    1 pear                      {pear}
    1 orange                    {orange}

如果您现在过滤正确:

Get-Content -Path C:\temp\Fruits.txt | Group-Object | Where-Object {$_.Count -gt 1} | Select-Object -ExpandProperty Group

输出是这样的:

apple
apple
apple
apple
tomato
tomato
cucumber
cucumber

推荐阅读