Reputation: 271
I have a list in which several items are repeated. I need to identify those items and create a new list to include all the repeated items, but for every time they reoccur.
Here's the list:
apple
orange
pear
carrot
tomato
cucumber
apple
apple
apple
cucumber
tomato
Thats apple x4, tomato x2, cucumber x2 and the rest x1.
The desired new list would be:
apple
apple
apple
apple
tomato
tomato
cucumber
cucumber
This omits the ones that exist only once and lists the ones that exist more than once and every time they occur.
I have tried:
$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
This produces:
apple
apple
apple
cucumber
tomato
Which is one missing for each fruit.
Any thoughts please?
Upvotes: 2
Views: 1062
Reputation: 3046
By Comparing the both Objects and saving the difference you basically do a ($Unique - "each entry once")
. This is because you want the difference between the variable which holds all entries and the variable which holds each entry once.
A better solution to this offers Group-Object
. This groups all entries together so that you can look out for the one with multiple entries.
The Command Get-Content -Path C:\temp\Fruits.txt | Group-Object
outputs this:
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}
If you now filter correct:
Get-Content -Path C:\temp\Fruits.txt | Group-Object | Where-Object {$_.Count -gt 1} | Select-Object -ExpandProperty Group
The Output is this:
apple
apple
apple
apple
tomato
tomato
cucumber
cucumber
Upvotes: 8