Author Posts

July 2, 2015 at 1:53 am

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

July 2, 2015 at 3:55 am

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"

}

July 2, 2015 at 5:29 am

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    

July 2, 2015 at 8:57 pm

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

July 2, 2015 at 8:58 pm

@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

July 3, 2015 at 10:12 am

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

July 6, 2015 at 8:03 pm

I got this point. Thanks