-1

I'm trying to get a sum of objects that are counted in text file. For example, this is how my file looks like:

Total servers: 3 Total databases: 10 Total table spaces: 30

Total servers: 5 Total databases: 50 Total table spaces: 500

Total servers: 3 Total databases: 30 Total table spaces: 100

I will need to get the sum of databases, so it should be 90 total.

R_sol
  • 67
  • 1
  • 1
  • 7
  • 1
    Where's the code? [How to Ask](https://stackoverflow.com/help/how-to-ask) – AdminOfThings Jan 27 '21 at 22:00
  • You may start with the extraction of the numbers from text and turn them from strings to actual numbers. I'd recommend watching this video: [Sophisitcated Techniques of Plain Text Parsing](https://youtu.be/Hkzd8spCfCU) – Olaf Jan 27 '21 at 22:23
  • 2
    Did you notice that you actually already asked this: [https://stackoverflow.com/questions/65416910/how-to-count-objects-in-text-file-using-powershell](https://stackoverflow.com/questions/65416910/how-to-count-objects-in-text-file-using-powershell) – Olaf Jan 27 '21 at 22:24
  • Olaf - this is different ask, I'm asking on how to count the sum of numbers in the file. – R_sol Jan 27 '21 at 22:25

3 Answers3

2

Here's one way (presuming your data is in a file called list.txt):

$dbCount = 0
Get-Content "list.txt" | ForEach-Object {
  $matches = [Regex]::Matches($_,'Total databases: (\d+)',"IgnoreCase")
  if ( $null -ne $matches.Groups ) {
    $dbCount += $matches.Groups[1].Value -as [Int]
  }
}

With your sample data in list.txt, $dbCount will equal 90.

Bill_Stewart
  • 22,916
  • 4
  • 51
  • 62
0

Given the text file content as $inputString:

$array = $inputString.Split([Environment]::NewLine)
$regex = 'Total databases: (?<dbCount>)[0-9]+'
$sum = 0

ForEach $string in $array {
    $string -match $regex

    $sum = $sum + [int]$Matches.dbCount
}

References:

$sum contains the value that you are searching for.

Stefano Paviot
  • 130
  • 1
  • 6
0

You may do the following:

((Get-Content file.txt) -replace '^.*databases: (\d+).*$','$1' | Measure-Object -Sum).Sum
AdminOfThings
  • 23,946
  • 4
  • 17
  • 27