powershell - 识别列表中不止一次存在的所有项目并将它们全部列出
问题描述
我有一个列表,其中重复了几个项目。我需要识别这些项目并创建一个新列表以包含所有重复的项目,但每次它们再次出现。
这是列表:
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
每个水果都缺少一个。
请问有什么想法吗?
解决方案
通过比较两个对象并保存差异,您基本上可以执行($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
推荐阅读
- node.js - Ubuntu/基准本地主机(请耐心等待)...apr_socket_recv:连接被拒绝(111)
- javascript - '+ ((visible && "is-active") || "")' 是一个好习惯吗?
- python - 基于多个属性的智能合约中的搜索记录
- node.js - 如何从 JSON 解析中的 promise 获得响应?
- c++ - 为什么priority_queue pop函数不删除top元素?
- jquery - 为什么 JQuery .hide() 函数不能与引导微调器一起使用?
- django - Django FactoryBoy TestCase 处理嵌套对象创建
- android - java.lang.NullPointerException:在 Release Build 中抛出空异常
- django - 当 ForeignKey 不是自引用时,如何获取 Django 对象的所有祖先?
- java - 可以用给定的字符串数组形成给定的字符串吗?