14

I need to find the duplicate values in a text file using power shell let's say if the file content is

Apple
Orange
Banana
Orange
Orange

Desired output should be

Orange
Orange
2
  • Should it just return the duplicate if it is on the next line? I see Orange 3 times in the input, and only 2 times in the output.
    – Sjark
    May 5, 2017 at 15:46
  • 1
    @Sjark, my requirement was to know whether there are any duplicates in a file. So the output can print Orange two or three times works for me. Anyways thanks for looking into it.
    – vineel
    May 5, 2017 at 15:56

2 Answers 2

29

You can also use the Group-Object cmdlet to see if any lines occur more than once:

e.g.

Get-Content test.txt | Group-Object | Where-Object { $_.Count -gt 1 } | Select -ExpandProperty Name
1
2

Used the Commands mentioned below and it worked.

PS C:\Projects> $OriginalContent, $UniqueContent = (Get-Content .\File.txt), (Get-Content .\File.txt | Sort-object -unique)
PS C:\Projects> compare-object $originalcontent $uniquecontent

or to print the text and the count use the following command

PS C:\Projects> Get-Content .\File.txt | group-object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.