Repeating Duplicate count

This topic contains 6 replies, has 3 voices, and was last updated by Profile photo of PowerShell84 PowerShell84 1 year, 6 months ago.

  • Author
    Posts
  • #27039
    Profile photo of PowerShell84
    PowerShell84
    Participant

    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
    Profile photo of Matt Bloomfield
    Matt Bloomfield
    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
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    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
    Profile photo of PowerShell84
    PowerShell84
    Participant

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

  • #27084
    Profile photo of PowerShell84
    PowerShell84
    Participant

    @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
    Profile photo of Matt Bloomfield
    Matt Bloomfield
    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
    Profile photo of PowerShell84
    PowerShell84
    Participant

    I got this point. Thanks

You must be logged in to reply to this topic.