Search code examples
powershelltext-parsing

How can i get the sum of a line from a .txt file in powershell?


So, I have a textfile "numbers.txt" like this:

2 3 4 5
5 6
6 7 7
6 88 9 67 4
65 76 979 8
6 88 5 4 23

My question is, how can i get the sum of each line? What i tried to do:

$data=Get-Content -Delimiter " " numbers.txt
$data | % {
 $sum=0
 foreach($num in $_) {
 $sum+=$num
 }
 Write-Host $sum
 }

But it gives back weird numbers. I dont know how to separate the different numbers in each line and get the sum of them.


Solution

  • Here's a fast and concise PSv4+ solution that utilizes LINQ:

    (Get-Content numbers.txt).ForEach({ 
      [Linq.Enumerable]::Sum([int[]] ($_ -split ' ')) 
    })
    
    • (Get-Content numbers.txt) returns the input file's lines as an array of strings.

    • .ForEach({ ... }) executes a script block ({ ...}) for each input line.

      • [Linq.Enumerable]::Sum(...) sums the elements of an array (enumerable) of numbers.

      • $_ -split ' ' splits the input line at hand ($_) into (string) tokens by spaces, and converts the result to an array of integers ([int[]]).

    Here's a - slower - solution closer to what you attempted (works in PSv3- too):

    Get-Content numbers.txt | ForEach-Object {  # Process each line.
      $sum = 0 # initialize the sum (implicitly of type [int])
      foreach ($num in $_ -split ' ') { # Process all tokens on the line.
        # Note: Because $sum is [int]-typed, adding the *string* token at 
        #       hand implicitly converts it to [int].
        $sum += $num  
      }
      $sum # Output the sum - do NOT use Write-Host to output DATA
    }
    

    Both solutions yield the following:

    14     # 2 + 3 + 4 + 5
    11     # 5 + 6
    20     # ...
    174
    1128
    126
    

    As for what you tried:

    Get-Content -Delimiter " " numbers.txt

    This splits your entire file into a single array of number strings, ignoring line boundaries.

    Instead, you must use Get-Content as-is in order to process the file line by line, and then split each line into space-separated tokens to sum up.