Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I find matching string name in the same object and then add value that is contain on each of the matching property?

I created a powershell command to collect and sort a txt file.

Input example:

a,1  
a,1  
b,3  
c,4  
z,5  

The output that I have to get:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

a,2  
b,3  
c,4  
z,5  

Here is my code so far:

$filename = 'test.txt'
Get-Content $filename | ForEach-Object {
    $Line = $_.Trim() -Split ','
    New-Object -TypeName PSCustomObject -Property @{
        Alphabet= $Line[0]
        Value= [int]$Line[1]
    }
}

example with negative value input

a,1,1
a,1,2
b,3,1
c,4,1
z,5,0

>Solution :

  • Import your text file as a CSV file using Import-Csv with given column names (-Header), which parses the lines into objects with the column names as property names.

  • Then use Group-Object to group the objects by shared .Letter values, i.e. the letter that is in the first field of each line.

  • Using ForEach-Object, process each group of objects (lines), and output a single string that contains the shared letter and the sum of all .Number property values across the objects that make up the group, obtained via Measure-Object -Sum:

@'
a,1
a,1
b,3
c,4
z,5
'@ > ./test.txt

Import-Csv -Header Letter, Number test.txt |
  Group-Object Letter |
  ForEach-Object {
    '{0},{1}' -f $_.Name, ($_.Group | Measure-Object -Sum -Property Number ).Sum
  }

Note: The above OOP approach is flexible, but potentially slow.
Here’s a plain-text alternative that will likely perform better:

Get-Content test.txt |
  Group-Object { ($_ -split ',')[0] } |
  ForEach-Object {
    '{0},{1}' -f $_.Name, ($_.Group -replace '^.+,' | Measure-Object -Sum).Sum
  }

See also:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading