Welcome Forums General PowerShell Q&A Repeating Duplicate count

Viewing 6 reply threads
  • Author
    Posts
    • #27039
      Participant
      Topics: 10
      Replies: 9
      Points: 0
      Rank: Member

      Hi PowerShell,
      Here is my sample script:
      $input = @(Get-Content H:\aa.txt |ForEach-Object {($_ -replace “\s+”,”,”)} )
      $repeating = @($input | ForEach-Object{$_.split(‘,’)[1] } | group )
      $repeating

      where aa.txt:
      as aa
      af aa
      ag aa
      ch bb
      fe bb
      fe cc
      gh cc

      how to repeat duplicate count in element [1]?

      I want to display output like this as below:
      as,aa,1
      af,aa,2
      ag,aa,3
      ch,bb,1
      fe,bb,2
      fe,cc,1
      gh,cc,2

      Any Idea?
      Thanks

    • #27044
      Participant
      Topics: 1
      Replies: 302
      Points: 145
      Helping Hand
      Rank: Participant

      Nice litte puzzle. How’s this?:

      $input = @(Get-Content c:\matt\aa.txt |ForEach-Object {($_ -replace "\s+",",")} )
      
      $tmp = @()
      
      ForEach ($line in $input) {
      
         $element  = $line.split(',')[1]
         $tmp += $element 
         $count = ($tmp | where {$_ -eq $element}).count
      
         Write-Output "$line,$count"
      
      }
      
    • #27071
      Participant
      Topics: 11
      Replies: 1443
      Points: 1,773
      Helping Hand
      Rank: Community Hero

      What is that actual end goal? If it’s just to see how many of each item are in a column, you can just do this:

      $content = Import-CSV C:\Temp\test.txt -Delimiter " " -Header Column1, Column2
      $content | Group-Object -Property Column2 -NoElement | Sort-Object -Property Count -Descending
      

      Output:

      Count Name                     
      ----- ----                     
          3 aa                       
          2 bb                       
          2 cc    
      
    • #27083
      Participant
      Topics: 10
      Replies: 9
      Points: 0
      Rank: Member

      @Rob
      you are right about it but i need a unique count e.g
      aa 1
      aa 2
      aa 3

    • #27084
      Participant
      Topics: 10
      Replies: 9
      Points: 0
      Rank: Member

      @Matt i think there is a little bit problem
      as,aa,
      af,aa,2
      ag,aa,3
      ch,bb,
      fe,bb,2
      fe,cc,
      gh,cc,2

    • #27099
      Participant
      Topics: 1
      Replies: 302
      Points: 145
      Helping Hand
      Rank: Participant

      The output I get is what you were after, shown below. I’ve tested what I posted on Windows 7 with PS 3 and Windows 8.1 with PS 4.

      as,aa,1
      af,aa,2
      ag,aa,3
      ch,bb,1
      fe,bb,2
      fe,cc,1
      gh,cc,2
      
    • #27239
      Participant
      Topics: 10
      Replies: 9
      Points: 0
      Rank: Member

      I got this point. Thanks

Viewing 6 reply threads
  • The topic ‘Repeating Duplicate count’ is closed to new replies.